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
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 .
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. `