Control Flow Statements
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. Below are some decision-making statements.
Decision Making Statements
-
if Statement
The if statement checks the given condition. If the condition evaluates to be true then the block of code/statements will execute otherwise not.
Syntax
C#if (condition) { // code to be executed }Note: If the curly brackets { } are not used with if statements then the statement just next to it is only considered associated with the if statement.
Example
C#string name = "CIIT"; // Using if statement if (name == "CIIT") { Console.WriteLine("Welcome to CIIT Training Institute ❤️👨🏫..!"); }When to use: Use anifstatement when you want to execute code only when a particular condition is true. -
if-else Statement
Use this when we want one action to happen if the condition is true, and an alternative action to happen if it is false.
Example
C#int num = 20; if (num % 2 == 0) { Console.WriteLine($"The number {num} is an even."); } else { Console.WriteLine($"The number {num} is an odd."); }Real-World Example: An application can useif-elseto check whether a candidate is eligible or not eligible based on their age or marks. -
else if Statement (Multiple Conditions)
If you need to test multiple distinct conditions, you can chain them using else if. The computer checks them in order and runs the code for the first condition that evaluates to true.
Example
C#int percentage = 85; if (percentage >= 80) { Console.WriteLine("Grade: Excellent"); } else if (percentage >= 60) { Console.WriteLine("Grade: Good"); // This will execute } else if (percentage >= 40) { Console.WriteLine("Grade: Average"); } else { Console.WriteLine("Grade: Poor"); // Fail if no conditions match }Important: The conditions are checked from top to bottom. Once a condition becomes true, its block executes and the remainingelse ifconditions are skipped. -
Combining Conditions with Logical Operators
We can check multiple conditions inside a single if statement using logical operators:
- && (AND): Both conditions must be true.
- || (OR): At least one condition must be true.
- ! (NOT): Reverses the truth of the condition.
Example
C#int a = 10; int b = 20; int c = 30; if (a > b && a > c) { Console.WriteLine($"{a} is greatest"); } else if (b > a && b > c) { Console.WriteLine($"{b} is greatest"); } else if (a == b && b > c && c == a) { Console.WriteLine("all are equal"); } else { Console.WriteLine($"{c} is greatest"); }Example: Logical operators are useful when a decision depends on more than one condition.
Switch Case Statement
In C#, the switch statement is a control flow structure used to execute a specific block of code out of multiple choices. It is a cleaner, more readable alternative to an if-else if ladder when you are comparing one variable against a list of concrete values.
Traditional switch Statement
The traditional switch evaluates a variable (the expression) and matches it against various case labels.
Example
string priority = "High";
switch (priority)
{
case "Low":
Console.WriteLine("Fix within 7 days.");
break; // Exits the switch block
case "Medium":
Console.WriteLine("Fix within 48 hours.");
break;
case "High":
Console.WriteLine("Fix immediately!");
break;
default:
Console.WriteLine("Unknown priority level.");
break;
}
break statement exits the switch block after a matching
case is executed.
Grouping Multiple Cases
If multiple cases share the exact same code, you can stack them together without a break between them.
Example
char grade = 'B';
switch (grade)
{
case 'A':
case 'B':
case 'C':
Console.WriteLine("You passed!");
break;
case 'D':
case 'F':
Console.WriteLine("You failed.");
break;
default:
Console.WriteLine("Invalid grade.");
break;
}
Modern C# switch Expressions
Introduced in C# 8.0, the switch expression provides a much cleaner, more compact syntax when you want to return a value from the switch block.
Instead of case and break, it uses the lambda arrow (=>), and replacing default is the discard underscore (_).
Example
int dayNumber = 3;
// Elegant, single-statement evaluation
string dayName = dayNumber switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "Weekend / Unknown" // The discard pattern (default)
};
Console.WriteLine(dayName); // Outputs: Wednesday
Advanced Switch with Type Checking (is Pattern)
You can use switch to inspect the type of an object, combining the logic of the is operator with branching.
Example
object shape = new Circle(radius: 5);
switch (shape)
{
case Circle c:
Console.WriteLine($"Circle with radius {c.Radius}");
break;
case Rectangle r:
Console.WriteLine($"Rectangle of {r.Width}x{r.Height}");
break;
case null:
Console.WriteLine("Shape is null.");
break;
}
Example 🤓🌍
Control flow statements are commonly used in real-world applications for login validation, student grading, employee eligibility, order processing, menu selection, and business rules.
int marks = 75;
if (marks >= 80)
{
Console.WriteLine("Grade: A");
}
else if (marks >= 60)
{
Console.WriteLine("Grade: B");
}
else if (marks >= 40)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Fail");
}
Common Mistakes to Avoid
-
Do not confuse
=with==. -
Make sure conditions are written in the correct order
when using multiple
else ifstatements. - Use curly braces to make blocks clear and avoid accidental execution of only one statement.
-
Remember to use
breakin traditional switch cases where required. - Use switch when comparing one expression against multiple clear values.
Summary
Control flow statements control the execution path of a C# program
based on conditions. The if, if-else,
and else if statements are useful for decision making,
while the switch statement is useful when selecting
between multiple choices. Logical operators can also be combined
with conditions to create more powerful decisions.
Practice Questions
- Write a program to check whether a number is positive or negative.
- Write a program to check whether a number is even or odd.
- Write a program to find the greatest of three numbers.
-
Write a program to calculate grades using
else if. -
Create a menu-driven program using a traditional
switchstatement. - Create a program using a modern C# switch expression.