C do while loop


do...while loops are almost same like while loops, except the condition is checked at the end of the loop, instead of at the beginning. Therefore the code in the do while loop will always be executed at least once. The general form is shown below :




}while (condition)

The sequence of operations is as follows :

1. execute the code within the braces

2. check the condition (boolean expression) and if it is true, go to step 1 and repeat

3. this repetition continues until the condition (boolean expression) evaluates to false.

See the flowchart :

c do while flowchart

Nested do while loop

The following program will print out a multiplication table of numbers 1,2,…,n. The outer do while loop is the loop responsible for iterating over the rows of the multiplication table. The inner loop will, for each of the values of colnm, print the row corresponding to the colnm multiplied with rownm. Here we use the special "\t" character within printf() function to get a clear output.

  1. #include <stdio.h>  
  2. main()  
  3. {  
  4. int rownm,nrow,colnm;  
  5. rownm=1;  
  6. colnm=1;  
  7. printf("Input number of rows for the table : ");  
  8. scanf("%d",&nrow);  
  9.  do  
  10.  {  
  11.   colnm=1;  
  12.   do  
  13.     {  
  14.     printf("%d\t",rownm*colnm);  
  15.       colnm++;  
  16.     }  
  17.   while(colnm<=nrow);  
  18. rownm++;  
  19. printf("\n");  
  20.  }  
  21.  while(rownm<=nrow);  
  22. }  


do while multiplication