In this tutorial, you will learn about c programming while and do while loop and how they are used in programs along with examples.
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.
C programming supports 3 types of looping:
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.
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.
[adsense1]
Sample Program: C program to print the sum of first 5 natural numbers
#include <stdio.h> int main () { int sum = 0, i = 1; //initialization of counter variable i while(i <= 5) //loop to be repeated 5 times { sum = sum+i; i++; //increment of countervariable } printf("sum of first 5 natural numbers = %d",sum); return 0; } //end of program
Output
sum of first 5 natural number = 15
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
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.
do
{
//block of code to be executed
} while (condition);
C program to print sum of first 5 natural numbers using do..while loop
#include <stdio.h>
int main ()
{
int sum = 0, i = 1; //initialization of counter variable i
do
{
sum = sum+i;
i++; //increment of counter variable
}while(i <= 5); //coondition of do while
printf("sum of first 5 natural numbers = %d",sum);
return 0;
} //end of program
Output
sum of first 5 natural numbers = 15