Else-if statements
An
else ... ifstatement allows us to check another condition if the previousifcondition was false.
Importantly, the code inside an else if block will only run if the previous
if condition was false. Even if the else if condition is true, it won’t run
if the previous if condition was true.
We can write this using words like this:
- Check
condition1:- If
condition1is true, run the code inside theifblock. - If
condition1is false, checkcondition2:- If
condition2is true, run the code inside theelse ifblock. - If
condition2is false, skip theelse ifblock [and move on to the next else if or else block, if any].
- If
- If
Basic syntax
Section titled “Basic syntax”if (condition1) { // Code to run if condition1 is true} else if (condition2) { // Code to run if condition1 is false and condition2 is true}We can have multiple else if statements to check multiple conditions in
sequence:
if (condition1) { // Code to run if condition1 is true} else if (condition2) { // Code to run if condition1 is false and condition2 is true} else if (condition3) { // Code to run if condition1 and condition2 are false and condition3 is true}Remember that, for example,
condition3will only be checked if bothcondition1andcondition2are false.
Example: positive, negative, or zero
Section titled “Example: positive, negative, or zero”Suppose we have an if statement that checks if a number is positive:
int number = 10;if (number > 0) { Console.WriteLine("The number is positive.");}But what if we also want to check if the number is negative or zero? We can use else-if statements to handle these additional conditions.
int number = -5;if (number > 0) { Console.WriteLine("The number is positive.");} else if (number < 0) { Console.WriteLine("The number is negative.");} else if (number == 0) { Console.WriteLine("The number is zero.");}Output:
The number is negative.In this example:
- The first
ifchecks ifnumberis greater than 0. Sincenumberis -5, this condition is false. - The program then checks the
else ifcondition to see ifnumberis less than 0. This condition is true, so it prints “The number is negative.” - The last
else ifcondition is not checked because one of the previous conditions was true.
You may realise that, if the number is not positive and not negative, it must be zero. So we don’t actually need to check the last condition - and we’ll learn how to do that next!