Theory
A program that lies
Rahul scored 20, and the result program printed Pass:
if (marks >= 35);
printf("Pass");
It compiles, yet one character is lying. Which one?
Think first
Find the liar
Type the character you suspect.
Show the answer
The semicolon after (marks >= 35). It ends the if with an empty statement, so the printf is outside the if and runs for everyone.
Theory
if, else, else if
if (condition) { } runs its block only when the condition is true, which in C means nonzero. else { } adds a second road, so exactly one of the two runs. Chain else if rungs and you get a ladder, checked from the top.
Practical
The grade ladder
#include <stdio.h>
int main() {
int marks = 65;
if (marks >= 70) {
printf("Grade A\n");
} else if (marks >= 60) {
printf("Grade B\n");
} else if (marks >= 35) {
printf("Grade C\n");
} else {
printf("Fail\n");
}
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
In the ladder above, marks is 65. What does it print?
- Grade A
- Grade B
- Grade B, then Grade C
- Grade C
Show the answer
Grade B
65 >= 60 is the first true rung, so Grade B prints and the ladder stops; 65 >= 35 is never tested.
Think first
Flip the ladder
Reverse the rungs: >= 35 first, >= 70 last. What does a topper with 92 get?
Show the answer
Grade C. 92 >= 35 is true on the first rung, so the ladder stops there, with no error and no warning. Put the strictest rung first.
Theory
An if inside an if
A nested if sits inside another if's block, so it runs only after the outer yes. Without braces, an else pairs with the nearest unmatched if, so use braces.
Practical
Nested if
#include <stdio.h>
int main() {
int marks = 80;
if (marks >= 35) {
printf("Pass\n");
if (marks >= 75) {
printf("Distinction\n");
}
} else {
printf("Fail\n");
}
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Think first
Trace it
marks is 80 in the program above. Type everything it prints.
Show the answer
Pass, then Distinction. The inner if is one more statement inside the outer block, so it adds a line; it does not replace Pass.
Practical
Exam-style: predict the output
#include <stdio.h>
int main() {
int x = 0;
if (x = 5)
printf("Five");
else
printf("Zero");
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: what is the output of the program above?
- Five
- Zero
- A compile error
- Nothing is printed
Show the answer
Five
x = 5 assigns 5 to x, and that value, 5, is nonzero, so the condition is true. Reading = as == gives the wrong answer, Zero.
Summary
Key takeaways
- if runs its block only when the condition is nonzero.
- A ladder runs only its first true rung, so put the strictest first.
- A nested if waits for the outer yes; else pairs with the nearest unmatched if.
- Memory hook: no semicolon after if, == to compare.