C# provides several conditional statements to control the flow of execution of a program. The following are the most commonly used conditional statements in C#:
if (condition)
{
// Code to execute if condition is true
}
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
// Code to execute if all conditions are false
}
switch (variable)
{
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
...
default:
// Code to execute if variable doesn't equal any of the values
break;
}
Note that the break statement is used to exit the switch statement once a case is matched.
Example of if:
int x = 10;
if (x > 5)
{
Console.WriteLine("x is greater than 5");
}
Output:
x is greater than 5
Example of if-else:
int x = 3;
if (x > 5)
{
Console.WriteLine("x is greater than 5");
}
else
{
Console.WriteLine("x is less than or equal to 5");
}
Output:
x is less than or equal to 5
Example of else-if:
int x = 7;
if (x < 5)
{
Console.WriteLine("x is less than 5");
}
else if (x < 10)
{
Console.WriteLine("x is less than 10");
}
else
{
Console.WriteLine("x is greater than or equal to 10");
}
Output:
x is less than 10
In the above example, the first condition if (x < 5) is not true, so it moves to the next condition which is else if (x < 10). Since x is 7, this condition is true and the corresponding code block is executed. The else block is not executed because the previous conditions were already true.
Example of switch:
int day = 3;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
Console.WriteLine("The day is: " + dayName);
Output:
The day is: Wednesday
In the above example, we have a variable day with a value of 3. The switch statement checks the value of day and executes the corresponding case. Since day is 3, the third case is executed, which assigns the value “Wednesday” to the dayName variable. The break statement is used to exit the switch statement after the matching case is executed. If day does not match any of the cases, the default case is executed, which assigns the value “Invalid day” to the dayName variable. Finally, we print the value of dayName to the console.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.