Register

C for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Loops

Starting out11 min readLesson 5 of 5

5.1 while

A while loop tests its condition before each pass. If the condition is false at the start, the body never runs.

The counter in a while loop is an ordinary variable that you declare before the loop and update inside it. Something in the body has to move that value toward the exit condition. A loop whose condition never becomes false runs until you stop the program.

c
#include <stdio.h>

int main(void)
{
    int i = 5;

    while (i > 0) {
        printf("%d\n", i);
        i--;
    }
    printf("Liftoff!\n");
    return 0;
}

Output

5
4
3
2
1
Liftoff!

5.2 for

for collects the three parts of a counted loop on one line: initialise, test, and update.

The header runs in a fixed order. The initialisation happens once, the test runs before every pass, and the update runs after every pass. The loop stops when the test is false.

C99 and later allow the counter declaration inside the header, so the counter goes out of scope when the loop ends. All three parts are optional, and for (;;) repeats until a break runs.

c
#include <stdio.h>

int main(void)
{
    int sum = 0;

    for (int i = 1; i <= 10; i++) {
        sum += i;
    }
    printf("The sum of 1 to 10 is %d.\n", sum);
    return 0;
}

Output

The sum of 1 to 10 is 55.

5.3 do while

A do while loop tests at the bottom, so its body runs at least once. Use it when the body must produce a value before the loop can decide whether to repeat, such as reading input until the value is acceptable.

The semicolon after while (condition); is part of the statement. Leaving it out is a syntax error.

c
#include <stdio.h>

int main(void)
{
    int value = 3;

    do {
        printf("%d\n", value);
        value *= 2;
    } while (value < 40);

    return 0;
}

Output

3
6
12
24

5.4 break and continue

break leaves the innermost loop immediately. continue skips the rest of the current pass and moves to the next test.

In a for loop, continue still runs the update expression, so the counter advances. In a while loop, continue jumps straight to the test, and a counter that the skipped code would have updated can leave the loop stuck.

Both statements affect one loop level. To leave two nested loops, set a flag before the inner break and test that flag in the outer condition.

c
#include <stdio.h>

int main(void)
{
    int count = 0;

    for (int n = 1; n <= 20; n++) {
        if (n % 2 == 0) {
            continue;
        }
        if (n > 9) {
            break;
        }
        printf("%d\n", n);
        count++;
    }
    printf("Printed %d numbers.\n", count);
    return 0;
}

Output

1
3
5
7
9
Printed 5 numbers.

5.5 Nested loops

An inner loop completes its whole cycle for every pass of the outer loop, so the pass count multiplies. Two loops of five passes each produce twenty-five pairs.

Use a different counter name at each level. C lets an inner declaration shadow an outer one, and the shadowing hides mistakes.

A multiplication table is the standard shape: the outer loop walks the rows and the inner loop walks the columns.

c
#include <stdio.h>

int main(void)
{
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 3; col++) {
            printf("%4d", row * col);
        }
        printf("\n");
    }
    return 0;
}

Output

1   2   3
   2   4   6
   3   6   9

5.6 Common loop mistakes

  • Off-by-one: for (int i = 0; i <= 5; i++) runs six passes. Decide whether the limit is included before you write the test.
  • A while loop whose body never changes the tested variable runs forever.
  • Updating the counter in the body and in the for header doubles the step, so the loop skips values.
  • Declaring the counter as size_t, an unsigned type, breaks a countdown: for (size_t i = n; i >= 0; i--) never ends, because an unsigned value cannot drop below zero.

If a loop misbehaves, print the counter at the top of the body for one run. The values show whether the loop starts where you think and stops where you think.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between a `while` loop and a `do while` loop?

    A `while` loop tests before the body, so the body can run zero times. A `do while` loop tests after the body, so the body runs at least once.

  • 02When does a `for` loop run its update expression?

    After the body of each pass, before the next test. A `continue` in the body jumps to the update, so the counter still advances.

  • 03How do you leave two nested loops at once?

    `break` leaves only the innermost loop. Set a flag before breaking the inner loop and test it in the outer condition, or move the loops into a function and use `return`.