Control Flow
Nested If
Nested if statements refine a decision in stages.
nested branch
An inner `if` only runs after the outer condition has chosen that path.
classification
Multiple checks can turn one numeric value into a label.
Nested If
nested_if.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int score = 82;
const char *label = "unknown";
if (score >= 60) {
if (score >= 90) {
label = "honors";
} else {
label = "pass";
}
} else {
label = "retry";
}
printf("%s:%d\n", label, score);
return 0;
}
#include <stdio.h>
int main(void) {
int score = 45;
const char *label = "unknown";
if (score >= 60) {
if (score >= 90) {
label = "honors";
} else {
label = "pass";
}
} else {
label = "retry";
}
printf("%s:%d\n", label, score);
return 0;
}
#include <stdio.h>
int main(void) {
int score = 96;
const char *label = "unknown";
if (score >= 60) {
if (score >= 90) {
label = "honors";
} else {
label = "pass";
}
} else {
label = "retry";
}
printf("%s:%d\n", label, score);
return 0;
}
score ← 82, label ← unknown
3int main(void) {4 int score→ 82 = 82; //@score=45, 965 const char *label→ unknown = "unknown";if (score >= 60)
7if (score82 >= 60) {8 if (score >= 90) {label ← pass
9 label = "honors";10} else {11 label→ pass = "pass";12}printf("%s:%d ", label, score);
17 printf("%s:%d\n", labelpass, score82);18 return 0;19}outputpass:82
score ← 45, label ← unknown
3int main(void) {4 int score→ 45 = 45;5 const char *label→ unknown = "unknown";label ← retry
12 }13} else {14 label→ retry = "retry";15}printf("%s:%d ", label, score);
17 printf("%s:%d\n", labelretry, score45);18 return 0;19}outputretry:45
score ← 96, label ← unknown
3int main(void) {4 int score→ 96 = 96;5 const char *label→ unknown = "unknown";if (score >= 60)
7if (score96 >= 60) {8 if (score >= 90) {label ← honors
7if (score >= 60) {8 if (score96 >= 90) {9 label→ honors = "honors";10 } else {printf("%s:%d ", label, score);
17 printf("%s:%d\n", labelhonors, score96);18 return 0;19}outputhonors:96
Follow the Branches
scorestarts as82.- The outer check
score >= 60is true. - The inner check
score >= 90is false. - The inner
elsesetslabeltopass. - The program prints
pass:82. | score | outer check | inner check | label | | --- | --- | --- | --- | | 82 | true | false | pass | | 45 | false | not reached | retry | | 96 | true | true | honors |
Exercise: nested_if.c
Reproduce pass:82, then use the pinned score variants 45 and 96 to predict retry:45 and honors:96.