Many decisions have more than two outcomes: fare discounts by age, grades by marks, tax by income slab. C handles these by placing if statements inside one another (nesting) or by chaining them into an else if ladder.
Nested if–else
A nested if is an if or if–else statement placed inside the body of another if or else.
Syntax
if (condition1) { if (condition2) { block A /* condition1 true, condition2 true */ } else { block B /* condition1 true, condition2 false */ }} else { block C /* condition1 false */}
The else-if ladder
Syntax
if (condition1) block 1else if (condition2) block 2else if (condition3) block 3else block n /* none of the conditions was true */
The conditions are tested from top to bottom. The first true condition’s block runs, and the rest of the ladder is skipped. The final else is optional.
Because conditions are tested in order, each later test can assume the earlier ones were false. This keeps the conditions short.
The dangling else
When braces are omitted, which if does an else belong to? C’s rule: an else always pairs with the nearest preceding unmatched if in the same block. Indentation is ignored by the compiler.
C · dangling.c
#include <stdio.h>int main(void){ int a = 1, b = 1; if (a == 1) if (b == 0) printf("Hi\n"); else printf("Bye\n"); return 0;}
Output
Bye
Despite the indentation, the else belongs to if (b == 0). Since a == 1 is true and b == 0 is false, the inner else runs and prints “Bye”. Use braces to make the intended pairing explicit.
Key takeaways
A nested if places one decision inside another.
An else if ladder tests conditions in order and stops at the first true one.
The final else handles every case that no condition matched.
An else belongs to the nearest unmatched if; use braces to be safe.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write an else if ladder that prints the tax rate for an income: up to 3,00,000 → 0%; up to 7,00,000 → 5%; above that → 10%. Trace it for 5,00,000.
Show worked answer
if (income <= 300000) printf("0%%\n"); else if (income <= 700000) printf("5%%\n"); else printf("10%%\n"); (%% prints a percent sign). For 500000: the first test 500000 <= 300000 is false; the second test 500000 <= 700000 is true, so “5%” is printed and the rest of the ladder is skipped.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/decision-and-loop-control-statements/nested-if-and-the-else-if-ladder/ to read this page.