Nested If-Else in C

A nested if-else statement is an if or else if statement inside another if or else if statement. It allows checking multiple conditions sequentially.

Syntax

if (condition1) { if (condition2) { // Code executed if both condition1 and condition2 are true } else { // Code executed if condition1 is true and condition2 is false } } else { // Code executed if condition1 is false }

Example

int marks = 85; if (marks >= 50) { if (marks >= 80) { printf("Grade A"); } else { printf("Grade B"); } } else { printf("Grade C"); }

How It Works

  • The outer if condition is evaluated first.
  • If the outer condition is true, the inner if-else is evaluated.
  • If the outer condition is false, the outer else block runs.
  • Allows multiple levels of conditions for more precise decision-making.

Tips

  • Keep nested levels minimal to maintain readability.
  • Use proper indentation to visualize the nested structure.
  • Consider using else-if ladder if checking multiple exclusive conditions.
  • Always use braces `{}` to avoid logical errors.

Common Mistakes

  • Over-nesting, which makes code hard to read.
  • Missing braces `{}` leading to unintended code execution.
  • Confusing which else belongs to which if (the 'dangling else' problem).
  • Writing complex conditions without parentheses, causing incorrect evaluation.