Topic Overview

Welcome! Today, we're exploring C#'s special instructions: Conditional Looping, along with the break and continue statements. As we know, loops enable code to execute multiple times. Conditional looping, enhanced with break and continue, bolsters loop control, leading to flexible, efficient code. Grab your explorer hat, and let's get started!

The 'if' Statement

C#'s if statement sets condition-based actions for our code. Consider this simple example where the if statement decides which message to print based on the value of temperature:

int temperature = 15;
if (temperature > 20)
{
    Console.WriteLine("Wear light clothes."); // This will print if the temperature is over 20.
}
else
{
    Console.WriteLine("Bring a jacket."); // This will print otherwise.
}

We can also evaluate multiple conditions using else if. In other words, "If the previous condition isn't true, then check this one":

if (temperature > 30)
{
    Console.WriteLine("It's hot outside!"); // Prints if the temperature is over 30.
}
else if (temperature > 20)
{
    Console.WriteLine("The weather is nice."); // Prints if the temperature is between 21 and 30.
}
else
{
    Console.WriteLine("It might be cold outside."); // Prints if the temperature is 20 or below.
}

Note that if an else if condition evaluates to true, the subsequent blocks are not checked. The first true condition's block executes, and the entire chain is bypassed.

The 'break' Statement

We use the break statement whenever we want to exit a loop prematurely once a condition is met:

int[] numbers = {1, 3, 7, 9, 12, 15};

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] % 2 == 0)
    {
        Console.WriteLine("The first even number is: " + numbers[i]); // Prints the first even number.
        break; // Stops the loop after printing the first even number.
    }
    Console.WriteLine("Number: " + numbers[i]);
}
// Prints:
// Number: 1
// Number: 3
// Number: 7
// Number: 9
// The first even number is: 12
The 'continue' Statement

The continue statement bypasses the rest of the loop's code for the current iteration only:

for (int i = 0; i < 6; i++)
{
    if (i == 3)
    {
        continue; // Skips the print command for '3'.
    }
    Console.WriteLine(i); // Prints the numbers 0 to 5 except 3.
}
// Prints:
// 0
// 1
// 2
// 4
// 5
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal