C# Conditional Statements and Control Flow
Example: If-Else Statement
Here is an example that demonstrates the use of if
, else if
, and else
statements to check the value of a variable and print corresponding messages.
|
|
Explanation
If Statement
- The
if
statement checks if the condition inside the parentheses is true. - If
number > 10
is true, it executes the code block inside theif
statement.
1 2 3 4
if (number > 10) { Console.WriteLine("The number is greater than 10"); }
- The
Else If Statement
- The
else if
statement provides an additional condition to check if the initialif
condition is false. - If
number == 10
is true, it executes the code block inside theelse if
statement.
1 2 3 4
else if (number == 10) { Console.WriteLine("The number is equal to 10"); }
- The
Else Statement
- The
else
statement is executed if none of the precedingif
orelse if
conditions are true. - It provides a fallback action.
1 2 3 4
else { Console.WriteLine("The number is less than 10"); }
- The
Output
Given number = 10
, the output will be:
|
|
Additional Notes
- Multiple Conditions: You can have multiple
else if
conditions to handle more complex scenarios. - Logical Operators: You can use logical operators like
&&
(AND),||
(OR), and!
(NOT) to combine multiple conditions in a singleif
statement.
Example with Logical Operators
|
|
Switch Statement
The switch
statement is another way to control the flow of your program based on the value of a variable. It is often used when you have multiple specific values to compare.
Example: Switch Statement
|
|
Explanation
Case Statements
- Each
case
statement compares the value ofnumber
to a specific value. - If
number
matches the value, the corresponding code block is executed.
1 2 3
case 10: Console.WriteLine("The number is equal to 10"); break;
- Each
Default Statement
- The
default
statement is executed if none of thecase
conditions match. - It serves as a fallback.
1 2 3
default: Console.WriteLine("The number is less than 10"); break;
- The
Break Statement
- The
break
statement exits the switch block, preventing the execution of subsequent cases.
1
break;
- The
Output
Given number = 10
, the output will be:
|
|