C programming while and do while loop

In this tutorial, you will learn about c programming while and do while loop and how they are used in programs along with examples.

While and do while loop in c programming

Sometimes while writing programs we might need to repeat same code or task again and again.

For this C provides feature of looping which allows the certain block of code to be executed repeatedly unless or until some sort of condition is satisfied even though the code appears once in the program.

while loop in C

The while loop repeats the block of code until some sort of condition is satisfied.

For example:

while I have money in my account

keep shopping.

In this statement condition is: " I have money in my account " and the task is " keep shopping ". So until the condition is true shopping will be done repeatedly and when the condition becomes false task will be stopped.

Structure of while statement

while (condition)
{
//block of code to be executed
}

How while loops work in C then?

As shown in the above structure a condition is placed which determines how many times the code is to be repeated.

Before entering inside the while loop the condition is checked, and if it is true the code block inside while loop is executed and again after the operation condition is checked and the repetition of code is continued until the condition becomes false.

Following flowchart explains more accurately the concept of while loop in C programming.

Counter variable like i should be initialized before while loop otherwise compiler will report an error and if you forget to increase/decrease the counter variable used in condition, the loop will repeat forever and there will not be any output.

do while loop in C

do..while is a variant of while loop but it is exit controlled, whereas, while loop was entry controlled.

Exit controlled means unlike while loop in do..while first the code inside the loop will be executed and then the condition is checked.

In this way even if the condition is false the code inside the loop will be executed once which doesn’t happen in while.

Syntax of do while loop

do
{
//block of code to be executed
} while (condition);

Flowchart of do while loop

Example: Do while loop

C program to print sum of first 5 natural numbers using do..while loop