The do while loop
Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.
Simple Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
a=1;
do
{
printf("\nHello");
a = a + 1
}while(a<=5);
a=6;
do
{
printf("\n\nHi"); // 1 time
a = a + 1
}while(a<=5);
getch();
}
Output:
Hello
Hello
Hello
Hello
Hello
Hi
Description :
First the value of a is set to 1. Since it is do while loop, the do part will execute atleast one time.
Hence 'Hello' is printed and in the next statement the value of a is incremented and becomes 2. Now the while condition is checked which is true since 2 <=5 hence again the control goes to the do loop and print 'Hello' and the value of a is again increased which becomes 3. Similarly the process continous till the condition become false.
When the condition become false the control goes to the next statement in which value of a is changed to 6 and the next statement is second do while loop. Since it is do while, it print 'Hi',in the next statement the value is incremented and becomes 7. Next the while condition is checked which comes out to be false and hence the control terminates from the do while loop.
Note :
We will discuss more programs in our C programs section.
Prev NEXT
1 comments:
Great explanation of the do-while loop in C! It’s perfect for situations where you want to ensure that the loop executes at least once before checking the condition. If you're working on more complex control flows or optimizing your C code, RKE2 is a fantastic tool for managing containerized applications and improving your development workflow.
Post a Comment