In the previous chapter, we read about while loop
and its working. Herein this chapter, we shall read about the next loop
in C i.e, do while loop. This loop is similar to while loop. But, the
only difference is that do while loop at least execute the block of code
once irrespective of the condition either true or false. In do while
loop, firstly the block of code gets executed then the evaluation of
condition takes place. If the condition is true then the block of code
will again execute.
Syntax of do while Loop
do
{
--------------------------
Some Statements
--------------------------
}
while(condition);
Above is the syntax for do while loop. Now lets understand it with an example program.
WAP to print 1 to 10 using 'do while' loop
#include<stdio.h>
void main()
{
int no = 10, i=0;
do
{
i++;
printf("%d \n",i);
}
while(i < no);
}
Output : 1
2
3
4
5
6
7
8
9
10
Explanation for the above program:
Here, we have taken two integer variables as no(//number) and i. Variable no is initialized to 10 and variable i is initialized to 0 as you can see in the program. Then, it will come inside do and perform i++ i.e, value of i will be incremented by 1. In the next line, with the printf statement, it will print the value of i i.e, 1 and goes to next line as \n is there. Now, it will come to while and check the condition if i<no. Till here, i = 1 and no = 10. So, it will check as while(1<10) means the condition is true and it will again go to the do statement and again execute the block of code inside do. So, value of i will be 2 now and it will be printed. Similarly, it will print upto 10 and then check for while(10 < 10) i.e false and come out of the loop.
Syntax of do while Loop
do
{
--------------------------
Some Statements
--------------------------
}
while(condition);
Above is the syntax for do while loop. Now lets understand it with an example program.
WAP to print 1 to 10 using 'do while' loop
#include<stdio.h>
void main()
{
int no = 10, i=0;
do
{
i++;
printf("%d \n",i);
}
while(i < no);
}
Output : 1
2
3
4
5
6
7
8
9
10
Explanation for the above program:
Here, we have taken two integer variables as no(//number) and i. Variable no is initialized to 10 and variable i is initialized to 0 as you can see in the program. Then, it will come inside do and perform i++ i.e, value of i will be incremented by 1. In the next line, with the printf statement, it will print the value of i i.e, 1 and goes to next line as \n is there. Now, it will come to while and check the condition if i<no. Till here, i = 1 and no = 10. So, it will check as while(1<10) means the condition is true and it will again go to the do statement and again execute the block of code inside do. So, value of i will be 2 now and it will be printed. Similarly, it will print upto 10 and then check for while(10 < 10) i.e false and come out of the loop.
No comments:
Post a Comment