Making Choices & Repeating Actions: C# Control Flow
So far, our programs have executed commands in a straight line, from top to bottom. But the true power of software comes from its ability to make decisions and perform actions repeatedly based on changing conditions. This is called control flow.
Think of a recipe: it doesn't just list ingredients; it has instructions like "If the mixture is too dry, add water" or "Whisk continuously for 5 minutes." These conditional actions and repetitions are what make the recipe work.
In this lesson, we'll learn how to give your C# programs a brain to think 🤔 and a motor to repeat 🔁, using the essential building blocks of all application logic.
Calling the Shots – Conditional Statements
Often, your program will need to make decisions and execute different pieces of code based on whether certain conditions are met. These are handled by conditional statements.
The if Statement:
The simplest decision-making tool is the if statement. It allows you to execute a block of code only if a specified condition evaluates to true.
Its basic structure is:
if (yourCondition)
{
// Code to execute if yourCondition is true
}
Imagine checking if a player's score is high enough for a bonus:
int playerScore = 1500;
bool hasBonusCard = true;
if (playerScore > 1000)
{
Console.WriteLine("Congratulations! Your score is over 1000!");
// You could have more lines of code here
}
If playerScore is greater than 1000, the message is printed. If not, the code inside the curly braces { } is skipped entirely.
The if-else Statement:
What if you want to do one thing if the condition is true, and something else if it's false? That's what the if-else statement is for.
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
Let's check if a user is logged in:
bool isLoggedIn = false; // Try changing this to true!
if (isLoggedIn)
{
Console.WriteLine("Welcome back, valued user!");
}
else
{
Console.WriteLine("Please log in to access your account.");
}
One of these two messages will always print based on the value of isLoggedIn.
The if-else if-else Ladder:
For situations with multiple conditions to check in sequence, you can use an if-else if-else structure. C# checks each condition from top to bottom. The first one that is true has its code block executed, and the rest are skipped. If none are true, the final else block (if present) runs.
char grade = 'B';
if (grade == 'A')
{
Console.WriteLine("Outstanding!");
}
else if (grade == 'B')
{
Console.WriteLine("Very Good!");
}
else if (grade == 'C')
{
Console.WriteLine("Good effort.");
}
else if (grade == 'D')
{
Console.WriteLine("Needs improvement.");
}
else // Optional: if none of the above
{
Console.WriteLine("Invalid grade entered.");
}
These if structures are fundamental for directing your program's logic based on different states or inputs.
Too Many Choices – The Switch Statement
When you have a situation where you're checking a single variable against many possible constant values, a long chain of if-else if-else statements can become a bit unwieldy. For these cases, C# provides the switch statement as a cleaner alternative.
The switch statement evaluates an expression (usually a variable) and then matches its value against a series of case labels. When a match is found, the code block associated with that case is executed.
// variableToSwitchOn could be an int, char, string, enum, etc.
switch (variableToSwitchOn)
{
case constantValue1:
// Code to execute if variableToSwitchOn == constantValue1
break; // Important! Exits the switch statement.
case constantValue2:
// Code to execute if variableToSwitchOn == constantValue2
break;
// ... more cases ...
default: // Optional: if no other case matches
// Code to execute if none of the cases match
break;
}
Let's say we have a user menu choice represented by a number:
int menuChoice = 2;
switch (menuChoice)
{
case 1:
Console.WriteLine("Starting new game...");
break;
case 2:
Console.WriteLine("Loading game options...");
break;
case 3:
Console.WriteLine("Exiting game. Goodbye!");
break;
default:
Console.WriteLine("Invalid choice. Please select 1, 2, or 3.");
break;
}
Key parts of the switch statement:
case: Eachcaselabel specifies a constant value to compare against.break: This is crucial. When the code for a matchingcaseis done,breaktells C# to exit theswitchstatement. Withoutbreak, the execution would "fall through" to the nextcaseblock, which is usually not what you want (though there are advanced scenarios for intentional fall-through).default: This optional label specifies code to run if none of the othercasevalues match the switch expression. It's like the finalelsein anif-else ifchain.
When to switch?
A switch statement is often preferred over a long series of if-else if statements when you are comparing a single variable against several distinct, constant values (like integers, characters, strings, or members of an enumeration). It can make your code more readable and organized in such scenarios.
For more complex conditional logic (e.g., checking ranges or multiple different variables), if-else if is generally more flexible.
Doing it Again and Again – The Magic of Loops
Imagine you need to print "Hello!" five times, or process every item in a list of usernames. You could write Console.WriteLine("Hello!"); five times, but what if you needed to do it a thousand times? That would be incredibly tedious and error-prone!
This is where loops come to the rescue. Loops are fundamental control flow structures that allow you to execute a block of code repeatedly. C# offers several types of loops, each suited for different situations.
Loops are the workhorses that handle repetitive tasks, process collections of data, and make your programs much more powerful and efficient.
For Loop – Repeat a Set Number of Times
The for is your go-to loop when you know (or can calculate) in advance exactly how many times you want to repeat a block of code. It's very common for iterating a specific number of times or for stepping through elements in things like arrays (which we'll learn about later).
The basic syntax looks like this:
for (initializer; condition; iterator)
{
// Code to be repeated as long as the condition is true
}
Let's break down its three parts, separated by semicolons:
initializer: This part runs only once before the loop begins. It's typically used to declare and initialize a counter variable (often namedifor "index"). Example:int i = 0;condition: This boolean expression is checked before each iteration (including the first one). If the condition istrue, the loop body executes. If it becomesfalse, the loop terminates. Example:i < 5;iterator: This part runs after each iteration of the loop body. It's usually used to update the counter variable. Example:i++;(which is shorthand fori = i + 1) ori--;(i = i - 1).
Here's an example that prints numbers from 1 to 5:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Current number is: " + i);
}
// Output:
// Current number is: 1
// Current number is: 2
// Current number is: 3
// Current number is: 4
// Current number is: 5
In this loop, i starts at 1. The loop continues as long as i is less than or equal to 5. After each print, i is incremented.
While Loop – Repeat Until Condition Changes
What if you don't know exactly how many times you need to loop, but you want to keep repeating as long as a certain condition holds true? For that, we have the while loop.
The while loop checks its condition before each iteration. If the condition is true, the loop body executes. If the condition is false initially, the loop body might not execute at all.
The syntax is straightforward:
while (condition)
{
// Code to repeat as long as condition is true
// IMPORTANT: Something inside the loop should eventually make the condition false!
}
Let's look at a simple countdown example:
int countdown = 3;
Console.WriteLine("Preparing for blast off...");
while (countdown > 0)
{
Console.WriteLine(countdown + "...");
countdown--; // This is crucial! It changes the value of 'countdown'.
}
Console.WriteLine("Blast off! 🚀");
Here, the loop continues as long as countdown is greater than 0. Inside the loop, we print the countdown and then decrement countdown (countdown-- is shorthand for countdown = countdown - 1). Eventually, countdown will become 0, the condition countdown > 0 will be false, and the loop will terminate.
Heads Up! The Dreaded Infinite Loop
With while loops (and do-while loops, which we'll see next), you must ensure that something within the loop body eventually causes the loop's condition to become false. If the condition always remains true, you'll create an infinite loop, and your program will get stuck running that loop forever (or until you manually stop it). This is a common beginner mistake, so always double-check your loop conditions and how they change!
The while loop is perfect when the number of iterations isn't known beforehand but depends on some runtime condition.
Do-While Loop – Do It At Least Once
The do-while loop is a close cousin of the while loop. The main difference is that the do-while loop checks its condition after each iteration, not before. This means the body of a do-while loop will always execute at least once, regardless of whether the condition is initially true or false.
Here's the syntax (note the semicolon ; after the while (condition)):
do
{
// Code to repeat
// This block always executes at least one time.
} while (condition); // Condition checked here, after the first run.
When is this useful? Often when you need to perform an action and then check if it needs to be repeated. A common example is getting user input until it's valid:
string? userInput; // string? indicates it can be null
do
{
Console.WriteLine("Please type 'confirm' to proceed:");
userInput = Console.ReadLine(); // Read input from the user
} while (userInput != "confirm"); // Loop as long as they don't type "confirm"
Console.WriteLine("Confirmed! Proceeding to next step...");
In this case, the prompt "Please type 'confirm' to proceed:" will always be displayed at least once. The loop continues until the user types exactly "confirm".
A Sneak Peek – The Foreach Loop
There's one more very common and incredibly useful loop in C# called the foreach loop. I'm giving you a sneak peek now because it's a bit different: it's specifically designed to iterate over each item in a collection of items, like a list of names or an array of numbers.
Since we haven't officially covered collections like arrays or lists yet (they're coming up soon!), we won't dive deep. But just so you recognize it when you see it:
// Imagine 'testNames' is a collection holding several strings like:
string[] testNames = { "Login Test", "Search Test", "Checkout Test" };
// The foreach loop goes through each 'testName' in the 'testNames' collection
foreach (string testName in testNames)
{
Console.WriteLine("Running: " + testName);
}
The foreach loop is super convenient because you don't have to manage a counter variable (like i in a for loop). It just handles getting each item from the collection for you one by one. We'll revisit this in detail when we talk about arrays and lists!
Loop Control Basics – Break and Continue
Sometimes, while a loop is running, you might need to change its normal flow. C# provides two keywords for this: break and continue.
The break Statement:
When the break statement is encountered inside a loop (for, while, do-while, or even foreach) or a switch statement, it immediately terminates the innermost loop or switch statement it's in. Execution then continues with the statement immediately following the terminated loop/switch.
Imagine searching for a specific number in a sequence, and you want to stop as soon as you find it:
int numberToFind = 7;
bool found = false;
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Checking number: " + i);
if (i == numberToFind)
{
found = true;
Console.WriteLine("Found it!");
break; // Exit the for loop immediately
}
}
if (found)
{
Console.WriteLine("The number " + numberToFind + " was found.");
}
else
{
Console.WriteLine("The number " + numberToFind + " was NOT found.");
}
Once i becomes 7, the message "Found it!" is printed, and break causes the for loop to stop, even though i hasn't reached 10 yet.
The continue Statement:
The continue statement is a bit different. When encountered inside a loop, it skips the rest of the current iteration of the loop body and immediately proceeds to the next iteration. For for loops, this means the iterator step runs next. For while and do-while loops, the condition is evaluated next.
Imagine you want to process only the odd numbers in a range:
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0) // Check if 'i' is even
{
continue; // Skip the rest of this iteration if 'i' is even
}
Console.WriteLine("Odd number: " + i);
}
// Output:
// Odd number: 1
// Odd number: 3
// Odd number: 5
// Odd number: 7
// Odd number: 9
When i is even, continue is executed, and the Console.WriteLine for that iteration is skipped. While powerful, use break and continue judiciously, as overusing them can sometimes make loop logic harder to read and understand.
Key Takeaways
- Control flow statements like conditionals and loops allow your C# programs to make decisions and repeat actions, moving beyond simple top-to-bottom execution.
if,else if, andelsestatements execute different blocks of code based on whether specified boolean conditions are true or false.- The
switchstatement offers a clear way to branch execution when comparing a single variable against multiple distinct constant values. forloops are ideal for iteration when you know the number of repetitions upfront, whilewhileanddo-whileloops repeat as long as a condition holds (checked before and after the iteration, respectively).- The
foreachloop (which we briefly met) is excellent for iterating over items in a collection. breakimmediately exits a loop or switch, whilecontinueskips the current iteration and proceeds to the next.- Mastering these control flow structures is absolutely fundamental to writing any non-trivial C# program or sophisticated automation script.
Mastering the Flow
- Microsoft Docs: Selection statements (if, switch) The official guide to C# conditional statements.
- Microsoft Docs: Iteration statements (for, foreach, while, do) Detailed information on C# looping constructs.
- Microsoft Learn: Add decision logic to your code Learn to branch your code's execution path by evaluating Boolean expressions.