Control Flow in C#: If, Else, and Switch Statements
Control flow structures allow you to make decisions in your C# programs. This guide will cover the use of if, else, and switch statements for controlling the flow of your C# code.
If Statement
The if statement is used to execute code based on a condition. Here's the basic syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
Else Statement
The else statement is used in combination with if to execute code when the condition is false:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
int age = 15;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are not an adult.");
}
Switch Statement
The switch statement is used when you have multiple conditions to evaluate. It provides an efficient way to choose between different code blocks based on a value:
switch (value)
{
case case1:
// Code to execute for case1
break;
case case2:
// Code to execute for case2
break;
// ... more cases ...
default:
// Code to execute if no case matches
break;
}
Example:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("It's Monday.");
break;
case 2:
Console.WriteLine("It's Tuesday.");
break;
// ... more cases ...
default:
Console.WriteLine("It's an unknown day.");
break;
}
Conclusion
Control flow structures such as if, else, and switch statements are essential for making decisions and controlling the flow of your C# programs. You've learned the basic syntax and usage of these statements.
Practice using these control flow structures in your programs to make your C# code more dynamic and responsive to different conditions.