C While Loop

Execute code repeatedly based on conditions

🔄 What is a While Loop?

A while loop in C repeats code as long as a condition is true. It's perfect when you don't know exactly how many times to repeat, making it ideal for user input and conditional repetition.


// Simple while loop example
#include <stdio.h>

int main() {
    int count = 1;
    while(count <= 5) {
        printf("Iteration: %d\n", count);
        count++;
    }
    return 0;
}
                                    

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

While Loop Components

🎯

Condition

Boolean expression to check

while(x < 10)
📦

Loop Body

Code to execute repeatedly

{ printf("%d", x); }
⬆️

Update

Change condition variable

x++;
🛑

Exit

When condition becomes false

x >= 10

🔹 Basic While Loop Syntax

The while loop syntax in C checks a condition before each iteration, repeating the code block as long as the condition evaluates to true. The structure follows while (condition) { statements; } where the condition is tested first. For example, int i = 0; while (i < 5) { printf("%d ", i); i++; } prints numbers 0 through 4. The loop variable must be initialized before the loop and updated inside the loop body to eventually make the condition false. If the initial condition is false, the loop body never executes. This pre-test nature distinguishes while loops from do-while loops and makes them suitable for situations where zero iterations might be necessary.

while(condition) {
    // Code to execute
    // Don't forget to update the condition variable!
}

// Example: Sum numbers from 1 to 10
#include <stdio.h>

int main() {
    int i = 1, sum = 0;
    
    while(i <= 10) {
        sum += i;
        i++;
    }
    
    printf("Sum of 1 to 10 = %d\n", sum);
    return 0;
}

Output:

Sum of 1 to 10 = 55

🔹 Practical While Loop Examples

🔸 User Input Validation

#include <stdio.h>

int main() {
    int number;
    
    printf("Enter a positive number: ");
    scanf("%d", &number);
    
    while(number <= 0) {
        printf("Invalid! Enter a positive number: ");
        scanf("%d", &number);
    }
    
    printf("You entered: %d\n", number);
    return 0;
}

Sample Run:

Enter a positive number: -5
Invalid! Enter a positive number: 0
Invalid! Enter a positive number: 7
You entered: 7

🔸 Finding Digits in a Number

#include <stdio.h>

int main() {
    int num = 12345, digits = 0;
    
    while(num > 0) {
        digits++;
        num /= 10;
    }
    
    printf("Number of digits: %d\n", digits);
    return 0;
}

Output:

Number of digits: 5

🔹 Infinite Loop Warning

Forgetting to update the loop control variable creates an infinite loop that runs forever, potentially causing your program to freeze or crash. For example, int i = 0; while (i < 10) { printf("Hello"); } never terminates because i remains 0, keeping the condition always true. Always ensure your loop contains code that eventually makes the condition false, such as i++;, i--;, or modifying variables involved in the condition. Infinite loops also occur with conditions like while (1) or while (true), which should only be used intentionally with explicit break statements. When debugging, check that loop variables update correctly and termination conditions can actually be reached during execution.

⚠️ Avoid This:

int i = 1;
while(i <= 5) {
    printf("%d ", i);
    // Missing i++; - This will run forever!
}

Loop variable management is critical in C programming. One of the most common mistakes programmers make is forgetting to update or properly initialize the loop variable, which can cause infinite loops or skipped iterations. Always ensure your loop counter increments or decrements correctly before each iteration. This simple oversight can lead to program crashes, unexpected behavior, or resource exhaustion. Implementing proper loop control prevents logic errors and ensures your code executes predictably.

🔸 Correct Version:

int i = 1;
while(i <= 5) {
    printf("%d ", i);
    i++; // This prevents infinite loop
}

🧠 Test Your Knowledge

When does a while loop stop executing?