do while loop


In while loop the condition is checked "before the body of loop is executed", that’s why it is called entry controlled loop . The loop may not be executed until the condition is not satisfied at very first time.
In some programs it may be necessary to execute the body of the loop at very first time before checking the condition. In such situation, do-while loop is used. In "do-while loop the condition is checked after the loop is executed", that’s why it is called exit controlled loop.


Syntax of do-while loop

do
{
body of the loop
}
while (Test-condition) ;


NOTE:- In do-while loop semicolon (;) is used at the end.

On reaching the do-statement, First of all the body of loop will execute, after that at the end of the loop the test condition is checked. If the test condition is False, then the loop is terminated and if the test condition is True, then the program continues & the body of the loop execute once again. At the end of the loop the test condition will be checked again and this process will continue until the test condition becomes False.

Since the test condition is evaluated at the end of the loop, therefor do-while loop is executed at least once.


Example 1: Illustrating the use of do-while loop :


In the above example, first the loop will be executed than the condition is checked. As long as both of the conditions or relations are true, the body of loop will be executed.


Example 2: Write a program to print the multiplication table .


Output:

Enter the value of n_max(row) & m_max(column) for multiplication table
10
8
- - - - - - - -Multiplication Table- - - - - - - -
1 2 3 4 5 6 7 8
2 4 6 8 10 12 14 16
3 6 9 12 15 18 21 24
4 8 12 16 20 24 28 32
5 10 15 20 25 30 35 40
6 12 18 24 30 36 42 48
7 14 21 28 35 42 49 56
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72
10 20 30 40 50 60 70 80
- - - - - - - - - - - - - - - - - - - - - - - - - - - -


Explanation:-


The above program contains two do-while loop in nested form. The outer loop is controlled by the variable row & inner loop is controlled by the variable column.
For the given input n_max(row)=10 & m_max(column)=8, the outer loop which is controlled by the variable row is executed 10 times & the inner loop which is controlled by the variable column is executed 8 times. For each outer loop, the inner loop is executed m_max(8) times, so the inner loop is executed total of 10*8=80 times and prints the multiplication table. Here new line is used in outer loop to change line after each row. For columns we used %5d in printf to ensure space between two columns. `


`
Key points
  • In do-while loop semicolon (;) is used at the end.
  • do-while loop is also called as exit controlled loop.


Do You Know?