Do-while Loop in C++

Do while Loop in C++

  • In Computer Science do-while loop executes the loop body at least once irrespective of the condition and then executes body based on the condition
  • Definition: In a do-while first the loop body is executed and then the test condition is checked  as a result one time execution of loop body is assured even if the condition is false for the first time
  • These type of loops are called Exit control or post test loop

Example Program to Print numbers from 1-10 using a do-while loop

main()
{
int i=0;//initialisation expression
do//loop_body
{
cout<<"\t"<<i;
i++;//update expression
}
while(i<=10);//test condition
cout<<"\n control reached here";
}

O/P

0 1 2 3 4 5 6 7 8 9 10
control reached here
Do-while Loop in C++
  • loop executed for 11 times, 1 time without checking the condition and 10 times (true)with checking condition
  • the test condition is evaluated 11 times, it is true for the first 10 times (0<1 to 11<=11) and to becomes false and break the loop at 12 times i.e 12<11(false)

Execution Flow

  • Loop body i.e the do block is executed first without checking any condition then the test condition is checked
  • If it is true: control goes to do block and again executes the loop body
  • Again check the test condition and execute do block
  • Repeat above 2 steps until the condition becomes false
  • If it is false: control goes to the next line after the test condition

While V/s Do while

Do-while-Loop

  • Post Test Loop: Execute the loop body and then check the condition
  • In a do- while loop  even if the test condition is false for the first time itself then  loop body will  execute at least once
main()
{

do//loop_body
{
cout<<"trishaank";
}
while(false);//test condition false at first time
}

O/P

trishaank

While Loop

  • Pretest Loop: Check the condition first then execute the loop body
  • In a while loop  if the test condition is false for the first time itself then  loop body will not execute at least once
main()
{

while(false)//control doesn't  go inside 
{
cout<<"trishaank";
}

}

O/P

Empty screen

C++ program to find the sum of digits of a given number using a do-while loop

My intention here is to write a sum of digits program within a single line

main()
{
int n,rem=0,sum=0;
cout<<"enter a num:";
cin>>n;

do//loop body
{
sum=sum+(rem=n%10);//sum of digtits program in a single line
}

while(n=n/10);//any number other than 0 is considered as true
cout<<"\nsum is:"<<sum;
}

O/P

enter a number
123
sum is 6

C++ program to print alphabets from A-Z with their ASCII codes

main()
{

char i='A';//inialisation

do
{
cout<<i<<":"<<(int)i<<"\n";
i++;//ascii codes are incremented
}

while(i<='Z');//internally ascicodes are compared
}

O/P

A:65
B:66
C:67
D:68
E:69
F:70
G:71
H:72
I:73
J:74
K:75
L:76
M:77
N:78
O:79
P:80
Q:81
R:82
S:83
T:84
U:85
V:86
W:87
X:88
Y:89
Z:90

Please Login/Signup to comment