Else-If Ladder in C
The else-if ladder in C is used to check multiple conditions sequentially. When a condition evaluates to true, its corresponding block executes, and the rest are skipped.
Syntax
if (condition1) { // Code executed if condition1 is true } else if (condition2) { // Code executed if condition2 is true } else if (condition3) { // Code executed if condition3 is true } else { // Code executed if all conditions are false }
Example
int marks = 78; if (marks >= 90) { printf("Grade A"); } else if (marks >= 75) { printf("Grade B"); } else if (marks >= 50) { printf("Grade C"); } else { printf("Fail"); }
How It Works
- Conditions are checked sequentially from top to bottom.
- The first condition that evaluates to true executes its block.
- Once a true condition is found, the rest of the else-if blocks are skipped.
- The final else block executes only if none of the conditions are true.
Tips
- Use else-if ladder for multiple exclusive conditions instead of deeply nested if-else statements.
- Keep conditions simple and readable.
- Always include the final else block to handle unexpected cases (optional but recommended).
- Indent properly to visualize the ladder structure.
Common Mistakes
- Writing overlapping conditions that may never be executed.
- Omitting braces `{}` in multi-line blocks, leading to logical errors.
- Confusing nested if-else with else-if ladder (they are different in evaluation order).
- Using complex conditions without parentheses, causing unintended results.
Codecrown