Loading...

C essentialsControl Flow

Loops: for, while & do-while

12 min lesson

Next
  • A loop repeats a block of code many times without you writing it many times.
  • Loops matter because programs often need to process lists of items, count up to a limit, or repeat until something happens.
  • Think of a loop as a treadmill: you set the speed and duration, and the belt keeps moving until the timer stops it.
  • A for loop is best when you know how many times to repeat: for (int i = 1; i <= 5; i++) { ... }.
  • A while loop is best when you repeat as long as a condition stays true, and you may not know the count in advance.
  • A do-while loop runs the body at least once, then checks the condition, which is useful for menus and input validation.
  • The computer runs the initialization once, checks the condition, runs the body, updates the counter, and repeats until the condition is false.
  • The syntax is: for (init; condition; update) { ... } or while (condition) { ... } or do { ... } while (condition);.
  • A realistic use: summing a list of prices, or printing a countdown from 10 to 1.
  • A surprising detail: if the condition never becomes false, the loop runs forever and the program freezes; this is called an infinite loop.
  • The example program uses a for loop to sum the numbers 1 to 5, a while loop to count down, and a do-while to print at least once.
Keep in mind
  • Use for when the number of repeats is known, and while when it depends on a condition.
  • Always make sure the loop condition can eventually become false, or you get an infinite loop.
  • Remember that do-while runs the body at least once before checking.
  • Keep loop bodies small and focused; move complex work into functions later.
  • Loops unlock real power in your programs. Keep practicing!
main.c
#include <stdio.h>

int main(void) {
    // A for loop that adds the numbers 1 to 5
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        // Add the current i to the running total
        sum += i;
    }
    // Print the final sum: 1 + 2 + 3 + 4 + 5 = 15
    printf("Sum 1..5: %d\n", sum);

    // A while loop that counts down from 3 to 1
    int countdown = 3;
    while (countdown > 0) {
        // Print the current number
        printf("Countdown: %d\n", countdown);
        // Decrease by 1 so the loop eventually stops
        countdown--;
    }

    // A do-while loop that runs the body at least once
    int attempts = 0;
    do {
        // This line always runs at least once
        printf("Attempt: %d\n", attempts);
        attempts++;
    } while (attempts < 2);

    return 0;
}

What happens: Sum 1..5: 15 Countdown: 3 Countdown: 2 Countdown: 1 Attempt: 0 Attempt: 1

Breaking it down

for initialization

int i = 1

Runs once before the loop starts. It creates the counter and gives it a starting value.

for condition

i <= 5

Checked before each pass. If it is true, the body runs; if false, the loop ends.

for update

i++

Runs after each pass. It moves the counter forward so the condition can eventually become false.

while loop

while (countdown > 0)

Checks the condition first, then runs the body. The counter must be changed inside the body.

do-while loop

do { ... } while (attempts < 2);

Runs the body first, then checks the condition. The body always runs at least once.

Choosing the right loop

LoopBest whenChecks conditionRuns at least once?
forCount is knownBefore bodyNo, if false at start
whileCount unknownBefore bodyNo, if false at start
do-whileMust run onceAfter bodyYes, always

A helpful analogy

A loop is like a treadmill with a timer. You set how fast and for how long (the for loop), or you keep going until you feel tired (the while loop). A do-while is like taking at least one step before deciding whether to continue.

Nesting rules

  • 1.Every loop needs a way for its condition to become false, or it becomes an infinite loop.
  • 2.In a for loop, keep initialization, condition and update on the same line so the loop is easy to read.
  • 3.In a while loop, update the counter inside the body; forgetting this causes an infinite loop.
  • 4.A do-while ends with a semicolon after the while condition; forgetting it is a compile error.

Common mistakes

Forgetting to update the counter in a while loop

Avoid

while (i < 5) { printf("%d", i); // i never changes }

Use instead

while (i < 5) { printf("%d", i); i++; }

The condition stays true forever, so the program freezes. Always change something inside the body that affects the condition.

Off-by-one error in a for loop

Avoid

for (int i = 1; i < 5; i++) // runs 1..4

Use instead

for (int i = 1; i <= 5; i++) // runs 1..5

Using < instead of <= stops one step early. Decide whether the end value should be included and choose the operator to match.

Missing semicolon after do-while

Avoid

do { ... } while (x < 5)

Use instead

do { ... } while (x < 5);

The do-while statement ends with a semicolon. Without it the compiler reports an error on the next line.

Quick tips

  • •Print the counter inside the loop while debugging to see how it changes.
  • •Use i++ when you want the value before incrementing and ++i when the order does not matter.
  • •Try changing the loop limit in the example to see how the sum changes.
  • •If a loop never ends, press Ctrl+C in the terminal to stop the program.
  • •Keep the body short; if it grows long, consider moving part of the work into a function later.
Previous
Next