Home Tutorials C Tutorial While Loop
While Loop

While Loop


The while Loop

What is a while Loop?

The while loop is an entry-controlled loop. It repeats a block of code as long as a specified condition remains True.

Because the condition is checked before the code inside the loop runs, if the condition is False at the very start, the code block will never execute even once. This makes it perfect for situations where you don't know how many times the loop should run.

Syntax

while (condition) {
    // Statements to repeat
    update_expression; // Change the variable to eventually end the loop
}

Practical Examples

Example 1: Basic Counter

int i = 1;

while (i <= 5) {
    printf("Iteration: %d\n", i);
    i++; // Increment i to avoid an infinite loop
}

Example 2: User Input Loop

int number = 1;

// Keep asking for a number until the user enters 0
while (number != 0) {
    printf("Enter a number (0 to quit): ");
    scanf("%d", &number);
}
The Golden Rule: Always make sure your loop body contains an update expression (like i++ or scanf). If you forget to change the variable that the condition depends on, the condition will always be true, creating an infinite loop!
Example

🏋️ Test Yourself With Exercises

Take our quiz on While Loop to test your knowledge.

Browse Quizzes »