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 is true.
  • If none of the conditions are true, the else 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 is 90 or higher, it prints "Grade: A".
  • If the score is 80 or higher (but less than 90), it prints "Grade: B".
  • If the score is 70 or higher (but less than 80), it prints "Grade: C".
  • If none of these conditions are true, the else block executes and prints "Grade: F".

3. Flow of Execution

  1. The first condition is evaluated.
  2. If the first condition is true, the code inside the first if block is executed, and the rest of the conditions are ignored.
  3. If the first condition is false, the second condition is evaluated.
  4. The process continues with the subsequent else if blocks, evaluating each condition in sequence.
  5. If no conditions are true, the else 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 is 65 or greater to classify someone as a senior citizen.
  • If the age is not 65 or greater, it checks if the person is 18 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.