if and the else-if Ladder
Simple if, if-else, nesting, the else-if ladder, and the dangling-else rule that decides which else binds where.
Programs That Choose
Four chapters of straight-line programs end here. The if statement runs code conditionally, and with it every truth value you have been computing, comparisons, logical operators, scanf's return count, finally gets to decide something. This lesson covers the whole if family: the plain form, if-else, the else-if ladder that exams adore, and the one parsing rule that catches everyone once.
if and else
if (condition) {
/* runs when condition is non-zero */
} else {
/* runs otherwise */
}
The condition is any expression; zero means false, anything else true, exactly as chapter 3 established. The else part is optional. Course style puts braces on every branch, even single statements, because the notorious bug of an unbraced second line "inside" an if that it is actually outside of has cost the industry real money.
The first thing worth guarding is one you have been waiting to guard:
Two ideas in one program. The scanf check is the promise from chapter 4 kept: the return value is finally acted on, and a non-zero return from main reports failure to the operating system, ending the program early. From this lesson forward, every scanf in the course is checked like this. The second if then makes the actual decision.
The else-if Ladder
Chains of mutually exclusive ranges use else if, and the classic example is the one every exam sets, grading:
The ladder is evaluated top down and exactly one branch runs: the first true condition wins and the rest are skipped. That is why the conditions can be simple: by the time marks >= 75 is tested, marks >= 90 has already failed, so the branch really means "between 75 and 89". Ordering matters for the same reason; sort the ranges from highest to lowest (or lowest to highest with reversed comparisons), and never overlap them.
The final bare else is the safety net that catches everything below the last rung. Leaving it off is legal; forgetting that you left it off is the bug.
Nesting and the Dangling else
An if can live inside another if, and with braces the meaning is always visible. Without braces there is a rule to know, because exams test it deliberately:
/* WRONG in appearance: the indentation lies */
if (attendance >= 75)
if (marks >= 40)
printf("promoted\n");
else
printf("attendance too low\n");
The indentation suggests the else belongs to the first if; the language says otherwise: an else binds to the nearest unmatched if. This else pairs with if (marks >= 40), so "attendance too low" prints for a student with good attendance and failing marks, precisely wrong. The cure is mechanical: braces on every branch make the question unaskable. Course code does exactly that, and when an exam prints unbraced nested ifs, apply the nearest-if rule and ignore the indentation.
Conditions Worth Writing
The tools of chapter 3 all report for duty inside if. Compound conditions combine range checks: if (marks >= 0 && marks <= 100) validates before grading. Short-circuit order protects dangerous operands: if (games != 0 && scored / games > 2). And the ternary from chapter 3 remains the right tool when the choice is merely a value; use if when the choice is an action. One habit to carry from day one: if (marks = 100) assigns and is always true; the compiler warns, and the warning is always right.
Key Takeaways
if (condition) { } else { }: zero is false, non-zero is true; braces on every branch, always.- Check scanf where it happens:
if (scanf("%d", &x) != 1)with an early non-zeroreturnis the course's standard guard from now on. - The else-if ladder runs exactly one branch, first true condition wins; order ranges accordingly and end with a bare
else. - An unbraced
elsebinds to the nearest unmatchedif, whatever the indentation claims. - Combine conditions with
&&/||, lean on short-circuit order for safety, and reserve?:for choosing values.
How did you find this lesson?
Your rating helps us improve the content.
Create an account to track your progress and access interactive exercises. Already have one? Sign in.
if and the else-if Ladder - Quiz
Test your understanding of the lesson.
Practice Exercises
The Grading Ladder
Read a marks value and print its grade using an else-if ladder: 90 and above is A, 75 to 89 is B, 60 to 74 is C, 40 to 59 is D, below 40 is F. Guard the scanf first: if the input is not a number, print "invalid input" and return 1.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!