codescracker
c

C do-while Loop



« Previous Tutorial Next Tutorial »

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
 */

#include<stdio.h>
#include<dos.h>
#include<conio.h>
void main()
{
   char choice;
   struct date d;
   getdate(&d);
   clrscr();

   do
   {
      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);
      switch(choice)
      {
         case '1' :
            printf("You have chosen right language.");
            break;
         case '2' :
            printf("You have to learn a lot");
            break;
         case '3' :
            printf("Today's Date : %d/%d/%d", d.da_day, d.da_mon, d.da_year);
            break;
         case '4' :
            exit(1);
         default :
            printf("Wrong choice..!!\n");

      }
      printf("\n\n");
   }while(choice!=4 && choice!=getchar());

   getch();
}

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 »



© Copyright 2021. All Rights Reserved.

CodesCracker