Conditional Statements in C#: `if`, `else`, and `else if`
Master conditional logic in C# using `if`, `else`, and `else if` statements. This tutorial explains their syntax, how to implement conditional logic, and provides examples illustrating their use in controlling program flow based on different conditions.
Conditional Statements in C#: `if`, `else`, and `else if`
Conditional statements in C# control the flow of your program based on whether certain conditions are true or false. The most basic conditional statement is the `if` statement. `if-else` and `if-else if` (else if ladder) statements add more options to handle different conditions.
The `if` Statement
An `if` statement executes a block of code only if a specified condition is true:
if (condition) {
// Code to execute if the condition is true
}
If the `condition` is false, the code block is skipped.
Example: Simple `if` Statement
int number = 10;
if (number % 2 == 0) {
Console.WriteLine("Even number");
}
The `if-else` Statement
An `if-else` statement provides two code blocks: one for when the condition is true and another for when it's false:
if (condition) {
// Code for true condition
} else {
// Code for false condition
}
Example: `if-else` Statement with User Input
This example takes user input and checks if the number is even or odd:
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
if (number % 2 == 0) {
Console.WriteLine("Even");
} else {
Console.WriteLine("Odd");
}
The `if-else if` Ladder
An `if-else if` ladder (or `else if` chain) allows you to test multiple conditions sequentially. The first condition that evaluates to `true` has its associated code block executed. If none of the conditions are true, the final `else` block (if present) is executed.
if (condition1) { ... }
else if (condition2) { ... }
else if (condition3) { ... }
else { ... }
Example: Grade Calculation
Console.Write("Enter score (0-100): ");
int score = int.Parse(Console.ReadLine());
// ... (if-else if ladder to determine grade based on score) ...