C do-while Loop

Unlike the for and while loop, which test the loop condition at the top of the loop, but the do-while loop in C programming, checks its condition at the bottom of the loop.

With above statement, it means that the do-while loop always executes at least once, unlike the other two loops.

So, do-while loop is generally used in menu-driven program like Calculator Program, which gives options to the user whether he/she wants addition, subtraction, multiplication, etc. to perform the desired action accordingly. Following example illustrates the concept of do-while loop.

C do-while Loop Example

Here is an example program based on do-while loop in C programming.

/* C do-while Loop Example
 * This program illustrates the
 * concept of do-while loop in C

void main()
   char choice;
   struct date d;

      printf("1. Good News\n");
      printf("2. Bad News\n");
      printf("3. Today's Date\n");
      printf("4. Exit\n");
      printf("Enter your choice (1-4) : ");
      scanf("%c", &choice);
         case '1' :
            printf("You have chosen right language.");
         case '2' :
            printf("You have to learn a lot");
         case '3' :
            printf("Today's Date : %d/%d/%d", d.da_day, d.da_mon, d.da_year);
         case '4' :
         default :
            printf("Wrong choice..!!\n");

   }while(choice!=4 && choice!=getchar());


Here is the 2 sample run of this do-while loop example program in C.

c do-while loop

c do while loop

To print date in words in C language, refer print date in words.

C Online Test

« Previous Tutorial Next Tutorial »