No history yet

Control Flow Statements

Making Decisions in Code

So far, our code has run like a train on a single track—straight from top to bottom. But what if we need a fork in the road? Most programs need to react to different situations, making decisions based on the data they have. This is where control flow statements come in. They are the signals and switches that direct the path of execution in your code.

Control flow statements let your program evaluate a condition and run different code depending on whether the condition is true or false.

The most fundamental decision-maker is the if statement. It's simple: if a certain condition is true, then run a specific block of code. If it's not true, the program just skips that block and moves on.

int playerHealth = 10;

if (playerHealth <= 0)
{
    // This code only runs if playerHealth is 0 or less.
    Console.WriteLine("Game Over!");
}

What if you need a default action for when the condition is false? That's what else is for. It gives you an alternative path. You can also chain conditions together with else if to check for multiple possibilities in sequence.

int temperature = 15; // In Celsius

if (temperature > 30)
{
    Console.WriteLine("It's hot outside.");
}
else if (temperature > 10)
{
    Console.WriteLine("It's a pleasant day.");
}
else
{
    Console.WriteLine("It's cold, bring a jacket!");
}

// Output: It's a pleasant day.

The program checks each condition from top to bottom. As soon as it finds one that's true, it executes that block and ignores the rest of the if-else if-else chain.

For situations where you're checking the same variable against a list of possible values, an if-else if chain can get clumsy. A switch statement is often a cleaner choice. It evaluates a variable once and then jumps to the case that matches the value.

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent!");
        break;
    case 'B':
        Console.WriteLine("Good job.");
        break;
    case 'C':
        Console.WriteLine("You passed.");
        break;
    default:
        Console.WriteLine("Invalid grade.");
        break;
}

// Output: Good job.

Each case checks for a specific value. The break keyword is crucial; it tells the program to exit the switch block. Without it, the code would continue to execute the cases below it, which is rarely what you want. The default case is optional and acts like a final else, catching any values that don't match the other cases.

Repeating Actions with Loops

Sometimes you need to perform the same action over and over. Instead of copying and pasting your code, you can use a loop. Loops repeat a block of code as long as a certain condition remains true.

The most common type is the for loop. It's perfect when you know exactly how many times you want to repeat an action. A for loop has three parts in its definition: an initializer (runs once before the loop starts), a condition (checked before each iteration), and an iterator (runs after each iteration).

// This loop will print numbers from 0 to 4
for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Current count: " + i);
}

// Initializer: int i = 0
// Condition: i < 5
// Iterator: i++

But what if you don't know how many times you need to loop? Maybe you want to keep trying something until it succeeds. For that, the while loop is a better fit. It simply repeats a block of code as long as its condition is true.

int enemyHealth = 100;
int attackDamage = 15;

while (enemyHealth > 0)
{
    Console.WriteLine("Attacking! Enemy health is now " + enemyHealth);
    enemyHealth -= attackDamage; // Decrease health
}

Console.WriteLine("Enemy defeated!");

Be careful with while loops! If the condition never becomes false, you'll create an infinite loop, and your program will get stuck.

There's one more variation: the do-while loop. It's similar to a while loop, but with a key difference: the condition is checked after the code block runs. This guarantees the code inside the loop will execute at least once.

string password;

do
{
    Console.WriteLine("Enter your password:");
    password = Console.ReadLine();
} while (password != "correct_password");

Console.WriteLine("Access granted.");

// The prompt to enter a password will always show at least one time.

Controlling the Flow

Sometimes you need more granular control within your loops. C# provides two keywords for this: break and continue.

We already saw break in the switch statement. In a loop, break does something similar: it immediately exits the entire loop, regardless of the loop's condition.

for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // Stop the loop when i is 5
    }
    Console.WriteLine(i);
}

// This will only print numbers 0, 1, 2, 3, 4

The continue keyword is a bit different. Instead of exiting the whole loop, it just skips the rest of the current iteration and jumps to the beginning of the next one.

for (int i = 0; i < 5; i++)
{
    if (i == 2)
    {
        continue; // Skip this iteration when i is 2
    }
    Console.WriteLine(i);
}

// This will print 0, 1, 3, 4. It skips 2.

Finally, you can put control structures inside other control structures. This is called nesting. For example, you can have a loop inside another loop, or an if statement inside a for loop. This allows for complex logic, like processing a grid or searching multi-dimensional data.

// Loop through rows
for (int i = 1; i <= 3; i++)
{
    // Loop through columns
    for (int j = 1; j <= 3; j++)
    {
        Console.Write("(" + i + "," + j + ") ");
    }
    Console.WriteLine(); // New line after each row
}

/* Output:
(1,1) (1,2) (1,3) 
(2,1) (2,2) (2,3) 
(3,1) (3,2) (3,3) 
*/

With these tools, you can build programs that are dynamic and intelligent, capable of handling a wide range of tasks and conditions.

Time to check your understanding.

Quiz Questions 1/6

In an if-else if-else statement, what happens as soon as a condition evaluates to true?

Quiz Questions 2/6

Under which scenario is a switch statement generally a cleaner and more readable choice than a series of if-else if statements?

Mastering control flow is a huge step in learning to program. It's how you turn simple, step-by-step instructions into complex, decision-making logic.