Tutorial 6.2: do while Repetition Structure

do while Loop
The do while loop is similar to the while loop. In the while loop, the loop condition is tested at the beginning of the loop. The do while loop tests the loop condition at the end of the loop structure or after the body of the loop is executed. Thus in do while loop, the compounded statement will be executed at least once.

Lets look at an example of do while loop.
#include <stdio.h>

int main()
{
 int count = 0;
 do {
  printf("%d\n", count);
  ++count;
 }while(count < 10);
 return 0;
}
Sample output:

0
1
2
3
4
5
6
7
8
9

Explanation:

This is also a very simple program of do while loop. The function of the program is exactly the same as the example of while loop. We skip the counter declaration and initialisation since it is already covered in the previous example. We go straight to the do while loop structure.
do {
 printf("%d\n", count);
 ++count;
}while(count < 10);
Similarly, it contains two (2) statements action printing the value of count and ++count. Lets go through it line-by-line. When the do while is executed, it begins by executing the printf() function. Thus count is displayed on the monitor screen. Then count is incremented and it reaches the brace at the end of the loop. Here loop condition is tested and if it is true, it will go back up to the beginning and the body of the loop will be executed again. This action continues until the condition is false.

Next: for loop

1 comment:

Post a Comment