4.2. Loops: Do-While

While and for loops tests the termination condition at the top. By contrast, the third loop in C, the do-while, test at the bottom after making each pass through the loop body; the body is always executed at least once.

The syntax of the do is
do {
statement
} while(expression);

The statement is executed, then expression is evaluated. If it is TRUE, statement is evaluated again, and so one.

Do not use while loop inside do-while, because that causes trouble, use instead of that for loop.

Examples

First example converts a number to a character string.

/*itoa: convert n to characters in s*/
void itoa (int n, char s)
{
  int i, sign;
  if ((sign = 0) < 0)/*record sign*/ 
  n = -n;/*make n positive*/ 
  i = 0; 
  do/*generates digits in reverse order*/ 
  { 
    s[i+] = n % 10 + '0';/*get next digit*/ 
  } while((n /= 10) > 0);/*delete it*/
  if(sign < 0)
    s[i++] = '-';
  s[i] = '\0';
  reverse(s);/* this function defined earlier*/ 
}

Next example is menu of the program in loop.

#include <stdio.h>
int Program_A(){ printf("Program A \n"); }
int Program_B(){ printf("Program B \n"); }
int Program_C(){ printf("Program C \n"); }
int main()
{
  int selection;
  do
  {
    printf("Options: \n");
    printf("1.Program A \n");
    printf("2.Program B \n");
    printf("3.Program C \n");
    printf("0.Stop the Program \n");
    printf("Please select \n?");
    scanf("%d", &selection);
    switch (selection)
    {
      case 1: Program_A(); break;
      case 2: Program_B(); break;
      case 3: Program_C(); break;
      case 0: printf("This ends the program, thank you for the use.\n"); break;
      default: printf(" You did not make a right choice! \n"); break;
    }

  } while( selection != 0);
return 0;
}

NOTE! Exercises for that chapter  can be found in quizzes Exercises 4 and P3-4 where  these skills will also be tested. It is also important that the student does these examples above.