C# if else if else statement
The if-else if-else
statement in C# allows for checking multiple conditions in sequence. This control flow structure enables you to evaluate several conditions one by one, executing a corresponding block of code as soon as a condition evaluates to true
. If none of the conditions are met, the else
block runs by default.
1. Syntax of the if-else if-else
Statement
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else if (condition3)
{
// Code to execute if condition3 is true
}
else
{
// Code to execute if none of the conditions are true
}
condition1, condition2, condition3
: These are boolean expressions that are evaluated in order. The program checks the conditions one by one until it finds one that istrue
.- If none of the conditions are
true
, theelse
block is executed.
2. Example of if-else if-else
Statement
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
Explanation:
- In this example, the program checks the value of
score
. - If the
score
is90
or higher, it prints"Grade: A"
. - If the
score
is80
or higher (but less than90
), it prints"Grade: B"
. - If the
score
is70
or higher (but less than80
), it prints"Grade: C"
. - If none of these conditions are
true
, theelse
block executes and prints"Grade: F"
.
3. Flow of Execution
- The first condition is evaluated.
- If the first condition is
true
, the code inside the firstif
block is executed, and the rest of the conditions are ignored. - If the first condition is
false
, the second condition is evaluated. - The process continues with the subsequent
else if
blocks, evaluating each condition in sequence. - If no conditions are
true
, theelse
block (if present) is executed.
4. Example with Age-Based Classification
int age = 25;
if (age >= 65)
{
Console.WriteLine("Senior citizen");
}
else if (age >= 18)
{
Console.WriteLine("Adult");
}
else if (age >= 13)
{
Console.WriteLine("Teenager");
}
else
{
Console.WriteLine("Child");
}
Explanation:
- The program first checks if
age
is65
or greater to classify someone as a senior citizen. - If the age is not
65
or greater, it checks if the person is18
or older to classify them as an adult. - If the person is not an adult, it checks if they are
13
or older to classify them as a teenager. - If none of these conditions are true, the
else
block classifies them as a child.