</>CodexBash
C
CBeginner10 min

Loops with for, while and do while

Counting loops with for, condition loops with while and do while, break and continue, nested loops, and the off-by-one errors that cause most loop bugs.

A loop keeping a running totalstep 1/6
4
8
15
16
i = -x = -total = 0
total starts at 0, before the loop. The loop will visit each item once, left to right.

for#

The counting loop:

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

The three parts in the brackets are: what to do first (int i = 0), the condition checked before each round (i < 5), and what to do after each round (i++). Read it as "start at 0, keep going while i is below 5, add one each time".

Counting down, or in steps:

for (int i = 10; i > 0; i -= 2) {
    printf("%d ", i);     // 10 8 6 4 2
}

Adding up an array#

int nums[] = {4, 8, 15, 16, 23, 42};
int n = 6;
long long total = 0;
for (int i = 0; i < n; i++) {
    total += nums[i];
}
printf("%lld\n", total);   // 108

while#

When you do not know how many rounds there will be, loop while a condition holds:

int n = 4071, digits = 0;
while (n > 0) {
    n /= 10;
    digits++;
}

Something inside must move towards the end. If nothing changes, the loop never stops, and on a judge that shows up as Time limit exceeded.

do while#

Runs the body once before checking, which suits "do this, then repeat if needed":

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

break and continue#

for (int i = 0; i < n; i++) {
    if (nums[i] < 0) {
        break;          // leave the loop entirely
    }
    if (nums[i] % 2 == 1) {
        continue;       // skip the rest of this round
    }
    printf("%d\n", nums[i]);
}

Nested loops#

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

The inner loop runs completely for every round of the outer, so two loops over n items do n × n steps. That is fine for a thousand items and far too slow for a hundred thousand.

Off by one#

Most loop bugs are being one step out.

  • An array of n elements has positions 0 to n - 1. for (i = 0; i <= n; i++) reads nums[n], which does not exist. C will not stop you: it quietly reads whatever memory comes next, and the bug may show up somewhere else entirely.
  • Comparing each element with the next, stop one early: i < n - 1, then use nums[i] and nums[i + 1].
  • Going backwards: for (int i = n - 1; i >= 0; i--).

Check both ends by hand: what is i on the first round, and on the last?

Key points#

  • for (start; condition; step) is the counting loop.
  • while repeats while a condition holds; do while runs at least once.
  • break leaves; continue skips to the next round.
  • Positions run 0 to n - 1, and C does not check, so be exact.

Next: organising code into functions.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedRunning sumEasy
  2. Not startedBest day to buy and sellEasy
Create a free account to track your progress