Sunday, February 21, 2016

'do...while' Loop

'do...while' loop is similar to 'while' except that the loop test expression is evaluated after execution of the loop body. The syntax of 'do...while'is given below.
  1. do
  2. {
  3. Statement block
  4. } while(expression);
Also, note that there is a semicolon (;) that is followed by while statement. Since the condition expression of 'do...while' is evaluated after the execution of loop body, it is guaranteed that the loop body will be executed at least once even if the text condition is false.

'do...while' Loop Example in C

Below program prints the first 10 numbers starting from 0.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int index = 0;
  5. do
  6. {
  7. printf("%d\n", index++);
  8. } while(index < 10);
  9. }
  10.  
  11. Output:
  12. 0
  13. 1
  14. 2
  15. 3
  16. 4
  17. 5
  18. 6
  19. 7
  20. 8
  21. 9
If you replace the while condition with while(0), you will still get output 0 printed on your screen, since the test condition is evaluated after execution of loop body.

Entry Controlled Loops & Exit Controlled Loops

The 'for' loop and the 'while' loop are known as the entry controlled loops as the test condition is checked before executing the loop body. Because of that, if the test condition is evaluated to false, loop body will not get executed.
'do...while' loop is known as exit controlled loop since the loop test expression is evaluated after execution the loop body. Because of that the loop body will be executed at least once even if the test condition fails the first time.

No comments: