while Loop in C (original) (raw)

Last Updated : 8 Oct, 2025

The **while loop in C allows a block of code to be executed repeatedly as long as a given condition remains true. It is often used when we want to repeat a block of code till some condition is satisfied.

C `

#include <stdio.h>

int main() { int i = 1;

// Condition for the loop
while (i <= 5) {   
    printf("GfG\n");   
  
    // Increment i after each iteration
    i++;  
}

return 0;

}

`

Output

GfG GfG GfG GfG GfG

**Explanation: The above loop prints the text “GfG” till the given condition is true i.e. **i is less than **5. In each execution of the loop’s statement, it increments **i till **i is less than **5.

Syntax of while Loop

C `

while (condition) { // Body updation }

`

where,

Working of while Loop

Let's understand the working of while loop in C using the flowchart given below:

C While Loop

flowchart for while loop

We can understand the working of the while loop by looking at the above flowchart:

Examples of while Loop

The below examples show how to use a while loop in a C program:

Sum of First N Natural Numbers using While loop

C `

#include <stdio.h>

int main() { int sum = 0, i = 1;

while (i <= 10) {
  
    // Add the current value of i to sum
    sum += i;
  
    // Increment i
    i++;       
}

printf("%d", sum);
return 0;

}

`

Multiplication Table from 1 to 5

C `

#include <stdio.h>

int main() {

  // Initialize outer loop counter	
int i = 1;

// Outer while loop to print a multiplication
// table for all numbers up to 5
while (i <= 5) {

      // Initialize inner loop counter for each row
    int j = 1;

    // Inner while loop to print each value in table
    while (j <= 5) {
        printf("%d ", i * j);
        j++;
    }
    printf("\n");
    i++;
}
return 0;

}

`

Output

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

**Explanation: In the above program, one while loop is nested inside anther while loop to print each value in the table. This is called nesting of loops and why can nest as many while loops as we want in in C.

Infinite while loop

An infinite while loop is created when the given condition always remains true. It is generally encountered in programs where, the condition variable is not correctly updated or has some logic error.

C `

#include <stdio.h>

int main() {

// Infinite loop condition (1 is always true)
while (1) {   
    printf("GfG\n");
}

// This line is never reached due to infinite loop
return 0;  

}

`

**Output

GfG
GfG
.
.
_infinite

As seen in the above example, the loop will continue till infinite because the loop variable will always remain the same resulting in the condition that is always true.

Important Points about while loop