② Six code-reading questions
Execute the code mentally before choosing an answer. Read the explanation even if you get it wrong.
Q1. An else-if chain
int score = 85;
if (score >= 90) printf("S\n");
else if (score >= 80) printf("A\n");
else if (score >= 70) printf("B\n");
else printf("C\n");
What is the output?
S
A
A B C
B
Explanation: 85 >= 90 is false; 85 >= 80 is true, so the A branch runs. The remaining branches are skipped, even though later conditions might also be true. Output: A.
Q2. Confusing = with ==
int a = 3;
if (a = 0) printf("A\n");
else printf("B\n");
printf("a=%d\n", a);
What is the output?
A
a=3
B
a=3
A
a=0
B
a=0
Explanation: a = 0 is assignment: it stores 0 in a, and its value 0 is false. The else branch prints B, then the program prints a=0. For an equality test, write a == 0.
Q3. Combining range conditions
int a = 7;
if (0 <= a && a < 10) printf("in\n");
else printf("out\n");
What is the output?
in
out
Nothing
Compilation error
Explanation: With a=7, both 0 <= a and a < 10 are true, so && is true and the output is in. Do not write 0 <= a < 10: C parses that as (0 <= a) < 10.
Q4. Missing break in switch
int n = 2;
switch (n) {
case 1: printf("A ");
case 2: printf("B ");
case 3: printf("C ");
default: printf("D ");
}
What is the output?
B
B C D
A B C D
B D
Explanation: n=2 starts execution at case 2. Without break, execution falls through case 3 and default, printing B C D. End a case with break; when you want to stop there.
Q5. Which if owns the else?
int a = 0, b = 0;
if (a > 0)
if (b > 0) printf("both+\n");
else printf("a+ b-not+\n" );
else printf("a not+\n");
What is the output?
both+
a+ b-not+
a not+
Nothing
Explanation: The first condition a>0 is false. Each else belongs to the nearest unmatched if; in this code the final else belongs to the outer if, so the output is a not+. Braces make the intended grouping clear.
Q6. Only default matches
int n = 5;
switch (n) {
case 1: printf("one"); break;
case 2: printf("two"); break;
default: printf("other");
}
What is the output?
one
two
other
Nothing
Explanation: n=5 matches no case, so default executes and prints other. A default case provides a fallback for unmatched values.