else and else if
Learn else and else if chains for alternative cases.
else and else if
To run a different block when the if condition is false you use else. For more branches you build an else if chain: the first true condition's block runs, the rest are skipped.
For example, letter grades use if (score >= 90) { ... } else if (score >= 80) { ... } else { ... }. The else at the end is the 'none of the above' branch and runs unconditionally.
Nested if and readability
You can write another if inside an if block; this is called a nested if. Deep nesting, however, hurts readability, so an else if chain or switch is preferred.
For example, if (logged && admin) { ... } reads better than if (logged) { if (admin) { ... } }. Keeping conditions flat where possible simplifies the code.
Exercise Determine the letter grade
Declare a score variable with the value 85. With if, else if and else: print "A" for 90 and above, "B" for 80 and above, "C" otherwise. A score of 85 should yield 'B'.
Show example solution
if (score >= 90), else if (score >= 80), else. Wrap each body in braces.
Example solution:
using System;
class Program
{
static void Main()
{
int score = 85;
if (score >= 90) { Console.WriteLine("A"); }
else if (score >= 80) { Console.WriteLine("B"); }
else { Console.WriteLine("C"); }
}
}
Test yourself
-
Start the else branch
if (age >= 18) { Console.WriteLine("adult"); } ____ { Console.WriteLine("child"); }Show answer
if (age >= 18) { Console.WriteLine("adult"); } else { Console.WriteLine("child"); } -
With int score = 75; which output is printed?
int score = 75; if (score >= 90) Console.WriteLine("A"); else if (score >= 80) Console.WriteLine("B"); else Console.WriteLine("C");- A
- B
- C
- Error
Show answer
C — Correct. 75 clears neither 90 nor 80; the else prints 'C'.
-
Match each branch to its meaning
- if
- First condition
- else if
- Alternative condition
- else
- Fallback branch
- else if x3
- Three-way chain