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
ifstatement checks if the condition inside the parentheses is true. - If
number > 10is true, it executes the code block inside theifstatement.
1 2 3 4if (number > 10) { Console.WriteLine("The number is greater than 10"); }- The
Else If Statement
- The
else ifstatement provides an additional condition to check if the initialifcondition is false. - If
number == 10is true, it executes the code block inside theelse ifstatement.
1 2 3 4else if (number == 10) { Console.WriteLine("The number is equal to 10"); }- The
Else Statement
- The
elsestatement is executed if none of the precedingiforelse ifconditions are true. - It provides a fallback action.
1 2 3 4else { 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 ifconditions to handle more complex scenarios. - Logical Operators: You can use logical operators like
&&(AND),||(OR), and!(NOT) to combine multiple conditions in a singleifstatement.
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
casestatement compares the value ofnumberto a specific value. - If
numbermatches the value, the corresponding code block is executed.
1 2 3case 10: Console.WriteLine("The number is equal to 10"); break;- Each
Default Statement
- The
defaultstatement is executed if none of thecaseconditions match. - It serves as a fallback.
1 2 3default: Console.WriteLine("The number is less than 10"); break;- The
Break Statement
- The
breakstatement exits the switch block, preventing the execution of subsequent cases.
1break;- The
Output
Given number = 10, the output will be:
| |
