The Wayback Machine - https://web.archive.org/web/20250118005758/https://www.geeksforgeeks.org/c-while-loop/
Open In App

while Loop in C

Last Updated : 16 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Let’s take a look at an example:

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

The while loop syntax is as follows:

while (condition) {
// Body
updation
}

where,

  • Initialization: In this step, we initialize the loop variable to some initial value. Initialization is not part of while loop syntax but it is essential when we are using some variable in the test expression
  • Conditional: This is one of the most crucial steps as it decides whether the block in the while loop code will execute. The while loop body will be executed if and only the test condition defined in the conditional statement is true.
  • Body: It is the actual set of statements that will be executed till the specified condition is true.
  • Updation: It is an expression that updates the value of the loop variable in each iteration. It is also not part of the syntax but we have to define it explicitly in the body of the loop.

Flowchart of while loop in C

C While Loop

Working of while Loop

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

  1. STEP 1: When the program first comes to the loop, the test condition will be evaluated.
     
  2. STEP 2A: If the test condition is false, the body of the loop will be skipped program will continue.
     
  3. STEP 2B: If the expression evaluates to true, the body of the loop will be executed.
     
  4. STEP 3:  After executing the body, the program control will go to STEP 1. This process will continue till the test expression is true.

Example of while Loop

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

Calculate the Sum of First N Natural Numbers

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;
}

Output
55

Print 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 is always true. It is encountered by programmers in when

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

  • It is an entry-controlled loop.
  • It runs the block of statements till the conditions are satiated, once the conditions are not satisfied it will terminate.
  • Its workflow is firstly it checks the condition and then executes the body. Hence, a type of pre-tested loop.
  • This loop is generally preferred over for loop when the number of iterations is unknown.

While Loop in C – FAQs

How does a while loop work in C?

The while loop evaluates the condition at the start of each iteration. If the condition is true, the code inside the loop runs. After executing the code, the condition is checked again. If it’s still true, the loop continues. If the condition becomes false, the loop terminates.

What happens if the condition in a while loop is always true?

If the condition in a while loop is always true, the loop becomes infinite, meaning it will keep executing the same block of code forever unless it is interrupted by an external action like a break statement or the program’s termination.

Can I modify the loop counter inside a while loop?

Yes, you can modify the loop counter or any other variable inside a while loop. In fact, it’s essential to update the condition variable (like incrementing or decrementing) within the loop; otherwise, it could lead to an infinite loop if the condition never changes.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg