For video
tutorial you can see below video:-
👉A do while
loop is similar to while loop with one exception that it executes the
statements inside the body of do-while before checking the condition.
👉On the
other hand in the while loop, first the condition is checked and then the
statements in while loop are executed.
👉So you can say that if a condition is
false at the first place then the do while would run once, however the while
loop would not run at all.
👉A do...while loop
is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax:
The syntax of a do...while loop
in C programming language is :-
do {
statement(s);
} while( condition );
👉Notice that the conditional
expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.
👉If the condition is true,
the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Flow Diagram:
How does a do-While loop executes?
✔ Control falls into the do-while loop.
✔ The statements inside the body of the loop get executed.
✔ Updation takes place.
✔ The flow jumps to Condition
✔ Condition is tested.
⭐ If Condition yields true, goto Step 6.
⭐ If Condition yields false, the flow goes outside the loop
✔ Flow goes back to Step 2.
The following program illustrates the
working of a do-while loop:
⭐We are going to print a table of number 2
using do while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int num=1; //initializing the variable
clrscr();
do //do-while
loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
getch();
}
Output:
2
4
6
8
10
12
14
16
18
20
👉In the above example, we have printed
multiplication table of 2 using a do-while loop. Let's see how the program was
able to print the series.
✔ First, we have
initialized a variable 'num' with value 1. Then we have written a do-while
loop.
✔ In a loop, we have a
print function that will print the series by multiplying the value of num with
2.
✔ After each increment, the
value of num will increase by 1, and it will be printed on the screen.
✔ Initially, the value of
num is 1. In a body of a loop, the print function will be executed in this way:
2*num where num=1, then 2*1=2 hence the value two will be printed. This will go
on until the value of num becomes 10. After that loop will be terminated and a
statement which is immediately after the loop will be executed. In this case
return 0.
0 Comments
If any one want learn some specific program in Computer Languages, so They all can comment there program questions.