Skip to content

while loops

Read · 1 of 5

Check, run, check again

while (condition) { … } checks the condition; if it's true it runs the block, then checks again. When the condition becomes false, the program moves on.

Something inside the loop must change the condition, or it runs forever.

Read this lesson as text

Repeat while a condition stays true.

Check, run, check again

while (condition) { … } checks the condition; if it's true it runs the block, then checks again. When the condition becomes false, the program moves on.

Something inside the loop must change the condition, or it runs forever.

Adding 1 to 4

#include <stdio.h>

int main() {
    int i = 1, sum = 0;
    while (i <= 4) {
        sum += i;
        i++;
    }
    printf("%d\n", sum);
    return 0;
}
  1. Line 4: Start: i is 1, sum is 0.
  2. Line 6: 1 <= 4, so the body runs: sum becomes 1.
  3. Line 7: i goes up to 2.
  4. Line 6: 2 <= 4: sum becomes 3.
  5. Line 6: Then 3 is added: sum is 6.
  6. Line 6: Then 4: sum is 10.
  7. Line 5: i is now 5, and 5 <= 4 is false, so the loop ends.
  8. Line 9: Printed after the loop.

Digits, one at a time

#include <stdio.h>

int main() {
    int n = 507;
    while (n > 0) {
        printf("%d", n % 10);
        n /= 10;
    }
    printf("\n");
    return 0;
}

What does this print?

  • 705
  • 507
  • 75
Show the answer

705 Each turn prints the last digit (7, then 0, then 5) and chops it off with n /= 10.

Exercise: Sum from 1 to n

Read n and print 1 + 2 + … + n, using a loop.

Exercise: Count the digits

Read a positive whole number and print how many digits it has, using a loop.