while loop in C with flow diagram and example code

The while statement (Iteration statement) executes a statement or block of statements until the given condition is true.

Syntax:

while ( controlling expression )
{
//while loop body
}

Note: Curly Braces is optional for single statement.

 

Flow-chart of while loop in C

In the while loop, evaluation of the controlling expression takes place before each execution of the loop body.

 

while loop in c

How does the while loop work?

Step 1. The while loop evaluates the controlling expression.

Step 2. If the controlling expression is false, the body of the while statement is never executed, and control skips the while statement and jumps to the next statement in the program.

Step 3. If the controlling expression is true or any non zero value, then control jump within the body of while loop and execute the statements in a sequential way. Might be there is only a single statement attached with a while loop.

Step 4. After the execution of while loop statements, the process is repeated from step 1.

For example,

If you want to print a message “hello aticleworld” 6 times then while loop is your friend and it avoids writing the code 6 times for printing the message.

#include <stdio.h>

int main()
{
    int counter = 0;

    while(counter < 6) //controlling expression
    {
        printf("  Hello Aticleworld \n");

        ++counter; //increment counter variable
    }

    return 0;
}

Output:

while in c

 

How the above program works:

Step 1: First check while loop condition. The initial value of the counter is zero so the condition is true.

Step 2: Print the message “Hello Aticleworld” and increment the value of the counter by 1.

Step 3: After executing the while loop body, repeat the step1 and step2 until the value of the loop is less than 6.

while loop example in C_CPP

 

We can terminate the while loop using the break, goto, or return keyword within the while loop body. We can also terminate an iteration without exiting the while loop using the continue keyword.

#include<stdio.h>

int main()
{
    int counter = 0;

    while(counter < 5 )
    {
        if(counter == 2)
        {
            break; // terminate loop
        }
        printf("Value of counter = %d\n", counter);

        ++counter;
    }

    return 0;
}

 

Output:

Value of loop = 0
Value of loop = 1

 

Recommended Articles for you: