C ยท Chapter 14 of 45

C While Loop

The while loop repeats a block of code as long as its condition remains true. The condition is checked before each iteration, so the body might never execute if the condition starts false.

A related loop, do...while, checks the condition after the body runs, guaranteeing the body executes at least once.

Syntax
while (condition) {
  // code
}

do {
  // code
} while (condition);

while loop

while evaluates its condition first; if true, the body runs, then the condition is checked again. This continues until the condition becomes false.

do...while loop

do...while runs the body first, then checks the condition. This guarantees the loop body executes at least once, which is useful for menus or input validation.

Example 1 (c)
#include <stdio.h>

int main() {
  int i = 0;
  while (i < 3) {
    printf("%d\n", i);
    i++;
  }
  return 0;
}
Output
0
1
2

The loop prints i and increments it until i is no longer less than 3.

Example 2 (c)
#include <stdio.h>

int main() {
  int i = 5;
  do {
    printf("%d\n", i);
    i++;
  } while (i < 3);
  return 0;
}
Output
5

do...while runs the body once even though the condition (i < 3) is false from the start.

Key points

  • while checks its condition before running the body.
  • do...while checks its condition after running the body.
  • Forgetting to update the loop variable causes an infinite loop.
  • Loop conditions must eventually become false to end the loop.
๐Ÿ’ก Note: Always make sure something inside the loop changes the condition, or the loop will run forever.

๐Ÿ“ Quick Quiz

1. When is the while loop's condition checked?

2. What guarantees a do...while loop body runs at least once?

3. What is a common cause of an infinite while loop?