Control Flow
What is Control Flow?
Control flow is how your program decides which code to run and when. It's like a traffic light for your code - it directs the flow of execution based on conditions.
If/Else
Make decisions
Switch
Multiple choices
Ternary
Short conditions
The if Statement
The if statement checks a condition. If the condition is true, it runs the code inside the curly braces.
Basic if
if (age >= 18)
{
Console.WriteLine("Adult");
}
What if condition is false?
If the condition is false, the code inside is skipped.
// ===== SIMPLE IF =====
int age = 20;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
// Output: "You are an adult."
// ===== WITH MULTIPLE LINES =====
if (isLoggedIn)
{
Console.WriteLine("Welcome back!");
Console.WriteLine("You have 3 new messages.");
}
The if-else Statement
The if-else statement gives you two paths. If the condition is true, run the first block. If false, run the second block.
True Path
if (score >= 60) → "Pass"
False Path
else → "Fail"
// ===== IF-ELSE =====
int score = 75;
if (score >= 60)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
// Output: "Pass"
// ===== REAL-WORLD EXAMPLE =====
bool hasPermission = false;
if (hasPermission)
{
Console.WriteLine("You can delete this file.");
}
else
{
Console.WriteLine("You don't have permission.");
}
The if-else if-else Statement
When you have multiple conditions, use else if. It checks each condition in order until one is true.
// ===== MULTIPLE CONDITIONS =====
int grade = 85;
if (grade >= 90)
{
Console.WriteLine("A");
}
else if (grade >= 80)
{
Console.WriteLine("B");
}
else if (grade >= 70)
{
Console.WriteLine("C");
}
else if (grade >= 60)
{
Console.WriteLine("D");
}
else
{
Console.WriteLine("F");
}
// Output: "B"
// ===== IMPORTANT: Order Matters! =====
// Conditions are checked from top to bottom
// Once one is true, the rest are skipped
The Switch Statement
The switch statement is a cleaner way to check many specific values of a single variable. It's like a multiple-choice question.
When to use Switch
- Checking one variable against many values
- The variable has a limited set of possibilities
- You want cleaner code than multiple if-else
When NOT to use Switch
- Complex conditions with ranges
- When you need to check multiple variables
- When conditions use different operators
// ===== BASIC SWITCH =====
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of week");
break; // Don't forget break!
case "Friday":
Console.WriteLine("End of week");
break;
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend");
break; // Both Saturday and Sunday run the same code
default:
Console.WriteLine("Midweek");
break; // default runs when no case matches
}
// ===== SWITCH WITH NUMBERS =====
int month = 3;
switch (month)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
default:
Console.WriteLine("Invalid month");
break;
}
break at the end of each case.
Without it, code will "fall through" to the next case!
The Ternary Operator
The ternary operator (? :) is a short way to write an if-else
statement in one line. It's like a quick question: "If true, do this, else do that."
// ===== TERNARY OPERATOR SYNTAX =====
// condition ? value_if_true : value_if_false
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
// status = "Adult"
// ===== SAME AS THIS IF-ELSE =====
string status2;
if (age >= 18)
status2 = "Adult";
else
status2 = "Minor";
// ===== MORE EXAMPLES =====
bool isLoggedIn = true;
string greeting = isLoggedIn ? "Welcome back!" : "Please login.";
// ===== NESTED TERNARY (Use carefully!) =====
int score = 85;
string grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
When to Use Each
| Statement | Best For | Example |
|---|---|---|
| if | Single condition check | if (age >= 18) |
| if-else | Two possible outcomes | if (score >= 60) else |
| if-else if | Multiple related conditions | if (score >= 90) else if (score >= 80) |
| switch | Multiple specific values | switch (day) { case "Monday": ... } |
| Ternary | Simple one-line decisions | age >= 18 ? "Adult" : "Minor" |
Exercise: Grade Calculator
Task: Create a grade calculator that uses all types of control flow.
Instructions:
- Create a console application called "GradeCalculator"
- Ask the user to enter their test score (0-100)
-
Use if-else if to calculate the letter grade:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
- Use a switch to display a message based on the letter grade
- Use the ternary operator to check if the student passed
- Add validation to make sure the score is between 0 and 100
- Use
Console.ReadLine()to get user input - Use
int.Parse()orConvert.ToInt32()to convert to a number - Use
if (score >= 90)for the first condition - In the switch, use
case "A":etc. - Ternary example:
string result = passed ? "Passed" : "Failed";
Enter your test score (0-100): 85 Letter Grade: B Message: Good job! Result: Passed!
Key Takeaway
Control flow statements let you control which code runs and when. Use if for simple decisions, if-else for two paths, if-else if for multiple conditions, switch for many specific values, and ternary for quick one-line decisions.