Learn/C/5. Loops
Lesson 5 of 15
Sign in

C, lesson 5

Loops

Computers are good at doing the same thing many times without getting bored. C has three loops. They can all do the same jobs; you pick the one that reads most naturally.

The for loop

Use for when you know how many times to repeat, or you are counting through a range:

The parentheses hold three parts separated by semicolons:

  1. init (int i = 1) runs once before the loop starts. A variable declared here exists only inside the loop.
  2. condition (i <= 5) is checked before every pass. When it is false, the loop ends.
  3. step (i++) runs after every pass.

Counting down or in larger steps is just a different step:

The while loop

Use while when you don't know in advance how many passes you need, only when to stop:

If the condition is false at the start, the body never runs.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

The do-while loop

do { ... } while (condition); checks the condition after the body, so the body always runs at least once. It fits "do something, then ask whether to repeat". Note the semicolon at the end.

Leaving early: break and continue

  • break jumps out of the loop immediately.
  • continue skips the rest of this pass and goes on to the next one (in a for loop, the step still runs).

Reading until the input runs out

scanf returns the number of values it stored, and returns EOF (a negative number) when there is no input left. That makes a neat loop for "read numbers until there are none":

Comparing with == 1 stops both at the end of the input and at text that is not a number.

Infinite loops

while (true) or for (;;) loops forever, which is fine as long as something inside calls break. A loop that never ends by accident is a common bug: check that the condition can actually become false. On this site a runaway program is stopped after a few seconds and reported as a time-limit error.

Further reading

  • cppreference: for loop
  • cppreference: while loop
  • cppreference: do-while loop
  • cppreference: break and continue

Read one integer n and print its times table from 1 to 10, one line each, in the form n x i = result.

(All ten lines are printed; the ... just shortens the example.)

A fitness tracker sends one number per day: the steps walked. The list ends with 0, which is not a day. Read the numbers until the 0, then print how many days there were, the total steps, and how many days reached the goal of 10000 steps or more.

The numbers may be on one line or several. If the first number is 0, all three values are 0.

for (int i = 1; i <= 5; i++) {
    printf("Lap %d\n", i);
}
for (int t = 10; t > 0; t -= 3) {
    printf("%d ", t);      // 10 7 4 1
}
printf("\n");
int balance = 100;
int weeks = 0;
while (balance < 500) {
    balance += 75;
    weeks++;
}
printf("%d weeks\n", weeks);   // 6 weeks
for (int n = 1; n <= 10; n++) {
    if (n % 3 == 0) {
        continue;          // skip multiples of 3
    }
    if (n > 8) {
        break;             // stop completely after 8
    }
    printf("%d ", n);      // 1 2 4 5 7 8
}
int value;
int total = 0;
while (scanf("%d", &value) == 1) {
    total += value;
}
printf("Total: %d\n", total);
Input:
7
Output:
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Input:
8500 12000 10000 3000 0
Output:
Days: 4
Total: 33500
Goal days: 2