while loop in c

The while loop statement always appears at the beginning or end of a loop. The easiest type of loop that uses while is called the while loop

Format of while loop

while (condition)
{ block of one or more C statements; }

The condition is a relational test that is exactly like the relational test condition

The block of one or more C statements is called the body of the while loop. The body of the while loop repeats as long as the condition is true. This is the difference between a while loop statement and an if statement: The body of the if executes if the condition is true. The body of the if executes only once, however, whereas the body of the while loop can execute a lot of times

while loop example

If you want to repeat a section of code until a certain condition becomes false, while loop is the way to go

#include <stdio.h>
int ctr = 0;
while (ctr < 5)
printf("Counter is at %d.\n", ++ctr);
while (ctr > 1)
printf("Counter is at %d.\n", --ctr);
return 0;

The variable ctr is initially set to 0. The first time while executes, i is less than 5, so the while condition is true and the body of the while loop executes. In the body, a newline is sent to the screen and ctr is incremented. The second time the condition is tested, ctr has a value of 1, but 1 is still less than 5, so the body executes again. The body continues to execute until ctr is incremented to 5. Because 5 is not less than 5 (they are equal), the condition becomes false and the loop stops repeating. The rest of the program is then free to execute, leading to the second while loop that counts down from 5 to 1, when it eventually makes the second condition false and ends the loop

Leave a Comment