0
0
CHow-ToBeginner · 3 min read

How to Use While Loop in C: Syntax and Examples

In C, a while loop repeatedly executes a block of code as long as the given condition is true. The syntax is while(condition) { /* code */ }, where the condition is checked before each iteration.
📐

Syntax

The while loop syntax in C consists of the keyword while, followed by a condition in parentheses, and a block of code inside curly braces. The loop runs the code block repeatedly as long as the condition remains true.

  • while: keyword to start the loop
  • condition: a test expression that returns true or false
  • code block: statements to execute repeatedly
c
while (condition) {
    // code to execute
}
💻

Example

This example prints numbers from 1 to 5 using a while loop. It shows how the loop runs while the condition is true and stops when it becomes false.

c
#include <stdio.h>

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

Common Pitfalls

Common mistakes with while loops include forgetting to update the loop variable inside the loop, which causes an infinite loop, or using a condition that is always false, so the loop never runs.

Always ensure the condition will eventually become false to stop the loop.

c
#include <stdio.h>

int main() {
    int i = 1;
    // Wrong: missing i++ causes infinite loop
    /*
    while (i <= 5) {
        printf("%d\n", i);
    }
    */

    // Correct:
    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}
Output
1 2 3 4 5
📊

Quick Reference

Remember these tips when using while loops:

  • Check the condition before each loop iteration.
  • Update variables inside the loop to avoid infinite loops.
  • Use break to exit the loop early if needed.
  • while loops are good when the number of iterations is not known in advance.

Key Takeaways

A while loop runs as long as its condition is true, checking before each iteration.
Always update the loop variable inside the loop to prevent infinite loops.
Use while loops when you don't know how many times you need to repeat code.
The loop body must be enclosed in curly braces if it has multiple statements.
Use break to exit a while loop early if necessary.