0

C do…while Loop


The do…while loop is the third type of loop for C and other programming languages. This type of loop is not very often used. It’s similar to the while loop. Here is the format of the do…while loop:

do {
  statements...;
}
while (condition);

Below are the execution steps:

  1. All the statements are executed
  2. The condition is checked
  3. The statements are executed one more time if the condition is true
  4. Repeat the above steps until the condition becomes false

The difference between do…while loop and while loop is that while loop checks the condition before the statements are executed whereas the do…while loop checks the condition after the statement are executed. This means that do…while loop executes the statements at least once, while the while loop might not execute the statements at all based on its condition.

The following is the sample code for the do…while loop:

/*
 *
 * dowhile.c
 *
 * Program to demonstrate the use of the do...while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type;
 int album;    // Boolean

 do {
   printf("Album or single (a for album, s for single)? ");
   while (getchar() != 'n' && getchar() != EOF)
     printf("");
   scanf("%c", &type);
   if (type != 'a' && type != 's')
     printf("Errorn");
 }
 while (type != 'a' && type != 's');

 album = type == 'a';    // Convert to boolean

 if (album)
   printf("Albumn");
 else
   printf("Singlen");

 fflush(stdin);
 getchar();
}

Note that it’s the same code as the while loop. The difference is that the type variable is not initialized anymore since it uses do…while loop.

There are no posts related to C do...while Loop.