while loop in C

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


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 to write the code 6 times for printing the message.


while in c


How the above program works:

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

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

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


We can terminate 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.


Value of loop = 0
Value of loop = 1