CC · Lesson 3 of 8

Control Flow

C's control flow is the template every other language copied. If you've used any other language, this will feel familiar.

C
#include <stdio.h>

int main() {
    int score = 75;

    // if / else if / else
    if (score >= 90) {
        printf("A\n");
    } else if (score >= 80) {
        printf("B\n");
    } else if (score >= 70) {
        printf("C\n");
    } else {
        printf("Study more\n");
    }

    // Ternary operator
    char *result = (score >= 60) ? "Pass" : "Fail";
    printf("%s\n", result);

    // switch (only works on integer types)
    int day = 2;
    switch (day) {
        case 1:
            printf("Monday\n");
            break;  // REQUIRED — fallthrough is the default
        case 2:
            printf("Tuesday\n");
            break;
        case 6:
        case 7:  // multiple cases can share a body
            printf("Weekend\n");
            break;
        default:
            printf("Midweek\n");
    }

    // Logical operators
    int x = 5, y = 10;
    if (x > 0 && y > 0) printf("both positive\n");
    if (x < 0 || y < 0) printf("one is negative\n");
    if (!(x == y)) printf("not equal\n");

    return 0;
}
C
#include <stdio.h>

int main() {
    // for loop
    for (int i = 0; i < 5; i++) {
        printf("%d ", i);
    }
    printf("\n");  // 0 1 2 3 4

    // while loop
    int n = 10;
    while (n > 0) {
        printf("%d ", n);
        n -= 3;
    }
    printf("\n");  // 10 7 4 1

    // do-while — always runs at least once
    int count = 0;
    do {
        printf("count: %d\n", count);
        count++;
    } while (count < 3);

    // Nested loops and break/continue
    for (int i = 0; i < 5; i++) {
        if (i == 2) continue;  // skip 2
        if (i == 4) break;     // stop at 4
        printf("%d ", i);
    }
    printf("\n");  // 0 1 3

    return 0;
}