Back to course

Looping Structures: The 'while' loop

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 17: Looping Structures: The while Loop

Loops allow a set of instructions to be executed repeatedly until a specific condition is met. The while loop is the simplest and most flexible looping structure.

while Loop Syntax

c while (condition) { // Code block to be executed repeatedly // Make sure the condition eventually becomes false! }

How it Works (Entry-Controlled Loop)

  1. The condition is checked.
  2. If the condition is True (non-zero), the loop body executes.
  3. After the body executes, the condition is checked again.
  4. If the condition is False (0), the loop terminates, and control moves to the statement immediately following the loop.

Example: Counting to 5

c #include <stdio.h>

int main() { int count = 1;

while (count <= 5) {
    printf("Count: %d\n", count);
    count++; // CRITICAL: Update condition variable
}

printf("Loop finished.\n");
return 0;

}

Infinite Loops

If the condition in a while loop never becomes false, the program will run forever (an infinite loop), which usually requires manual termination.

c // Example of an infinite loop /* while (1) { // This will run forever since 1 is always True } */