Foundations
Conditionals
if and else choose which statements run based on a condition.
if
An `if` statement runs its block only when the condition is true.
else
An `else` block handles the opposite path.
Conditionals
conditionals.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 60) {
printf("pass:%d\n", score);
} else {
printf("retry:%d\n", score);
}
return 0;
}
#include <stdio.h>
int main(void) {
int score = 58;
if (score >= 60) {
printf("pass:%d\n", score);
} else {
printf("retry:%d\n", score);
}
return 0;
}
#include <stdio.h>
int main(void) {
int score = 95;
if (score >= 60) {
printf("pass:%d\n", score);
} else {
printf("retry:%d\n", score);
}
return 0;
}
score ← 72
3int main(void) {4 int score→ 72 = 72; //@score=58, 95if (score >= 60)
6if (score72 >= 60) {7 printf("pass:%d\n", score72);8} else {outputpass:72return 0;
12 return 0;13}
score ← 58
3int main(void) {4 int score→ 58 = 58;else
7 printf("pass:%d\n", score);8} else {9 printf("retry:%d\n", score58);10}outputretry:58return 0;
12 return 0;13}
score ← 95
3int main(void) {4 int score→ 95 = 95;if (score >= 60)
6if (score95 >= 60) {7 printf("pass:%d\n", score95);8} else {outputpass:95return 0;
12 return 0;13}
Follow the Branch
scorestarts at72.- C checks whether
score >= 60. 72 >= 60is true.- The pass branch runs.
- The program prints
pass:72. | score | comparison | stdout | | --- | --- | --- | | 58 | false |retry:58| | 72 | true |pass:72| | 95 | true |pass:95|
Exercise: conditionals.c
Reproduce pass:72, then use the pinned scores 58 and 95 to identify the branch and output.