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

score
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;
}
  1. score ← 72

    3int main(void) {4    int score→ 72 = 72; //@score=58, 95
  2. if (score >= 60)

    6if (score72 >= 60) {7    printf("pass:%d\n", score72);8} else {
    outputpass:72
  3. return 0;

    12    return 0;13}
  1. score ← 58

    3int main(void) {4    int score→ 58 = 58;
  2. else

    7    printf("pass:%d\n", score);8} else {9    printf("retry:%d\n", score58);10}
    outputretry:58
  3. return 0;

    12    return 0;13}
  1. score ← 95

    3int main(void) {4    int score→ 95 = 95;
  2. if (score >= 60)

    6if (score95 >= 60) {7    printf("pass:%d\n", score95);8} else {
    outputpass:95
  3. return 0;

    12    return 0;13}

Follow the Branch

  1. score starts at 72.
  2. C checks whether score >= 60.
  3. 72 >= 60 is true.
  4. The pass branch runs.
  5. 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.