student@ubuntu:~$
c-foundations Lesson 4 10 min read

If/Else, Switch & Loops

Branching, switch fall-through, and the three loop forms in C

Reading: Hanly & Koffman: §4.1–4.5 (pp. 174–206), §5.1–5.7 (pp. 236–276)

Quick check before you start: Do you know what happens if you forget break in a switch case? If not, read on. If you can, skip to Loops.

Practice this topic: C Control Flow skill drill

After this lesson, you will be able to:

  • Write if/else and else-if chains
  • Use switch statements with proper break placement
  • Explain switch fall-through and when it causes bugs
  • Choose between for, while, and do-while loops
  • Apply break and continue in loops

If/Else

Same syntax as Java. The condition must be in parentheses, and there is no boolean — zero is false, non-zero is true.

int score = 85;

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

You can omit braces for single statements, but do not. It invites bugs when you add a second line later.

Key Insight: C has no elif keyword like Python. It is else if — two separate words. The else starts a new block, and the if begins a nested check.

Switch Statements

Switch works on int and char values only. No strings, no floats.

char grade = 'B';

switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
        printf("Good\n");
        break;
    case 'C':
        printf("Average\n");
        break;
    default:
        printf("Unknown\n");
        break;
}

Fall-Through

If you omit break, execution continues into the next case. This is called fall-through, and it is almost always a bug.

int day = 3;

switch (day) {
    case 1:
        printf("Monday\n");
    case 2:
        printf("Tuesday\n");
    case 3:
        printf("Wednesday\n");
    case 4:
        printf("Thursday\n");
    case 5:
        printf("Friday\n");
        break;
    default:
        printf("Weekend\n");
}

With day = 3, this prints:

Wednesday
Thursday
Friday

Execution enters at case 3 and falls through case 4 and case 5 until it hits break. This behavior exists for intentional grouping (multiple cases sharing one body), but forgetting break is one of the most common C bugs.

/* Intentional fall-through: grouping cases */
switch (day) {
    case 1: case 2: case 3: case 4: case 5:
        printf("Weekday\n");
        break;
    case 6: case 7:
        printf("Weekend\n");
        break;
}

For, While, and Do-While

for

Use when you know the number of iterations.

for (int i = 0; i < 5; i++) {
    printf("%d ", i);
}
/* Output: 0 1 2 3 4 */

while

Use when the number of iterations depends on a condition.

int n = 1;
while (n <= 100) {
    n *= 2;
}
printf("%d\n", n);   /* 128 — first power of 2 over 100 */

do-while

Runs the body at least once, then checks the condition.

int input;
do {
    printf("Enter a positive number: ");
    scanf("%d", &input);
} while (input <= 0);

This is the right tool for input validation — you need to read at least one value before you can check it.

Break and Continue

break exits the nearest loop immediately. continue skips to the next iteration.

/* Print odd numbers 1-9 */
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;       /* skip even numbers */
    }
    printf("%d ", i);
}
/* Output: 1 3 5 7 9 */
/* Find first negative */
int arr[] = {3, 7, -2, 5};
for (int i = 0; i < 4; i++) {
    if (arr[i] < 0) {
        printf("Found negative at index %d\n", i);
        break;
    }
}

Check Your Understanding
What happens if you forget break after case 'A' in a switch statement?
AThe compiler gives an error
BOnly the code in case 'A' runs
CExecution falls through into the next case and keeps going until a break or the end of the switch
DThe switch exits automatically after the first matching case
Answer: C. Without break, C does not stop at the end of a case. It continues executing the statements in the next case, and the next, until it reaches a break or the closing brace of the switch. This is called fall-through. Java inherited this behavior from C, so you may have seen it before — but in C there is no compiler warning by default.

Nested Loops

When you place one loop inside another, the inner loop runs to completion for each iteration of the outer loop. This is how you work with grids, tables, and two-dimensional data.

/* Multiplication table (1-5) */
for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= 5; col++) {
        printf("%4d", row * col);
    }
    printf("\n");
}

The outer loop controls rows. For each row, the inner loop prints every column value, then the outer loop moves to the next line. With row = 3, the inner loop prints 3 6 9 12 15 before the outer loop advances to row = 4.

Compound Assignment Operators

When you update a variable based on its current value, compound assignment operators save repetition:

Operator Equivalent to Example
sum += x sum = sum + x sum += 5;
diff -= x diff = diff - x diff -= 3;
prod *= x prod = prod * x prod *= 2;
quot /= x quot = quot / x quot /= 4;
rem %= x rem = rem % x rem %= 10;

You have already been using i++, which is shorthand for i += 1. These operators appear constantly in loops that accumulate results.


What Comes Next

You can now make decisions and repeat actions. Next, you will organize code into functions, learn about scope, and see how recursion works in C.