Skip to main content

11. Do-while Loop

 

C Loops

The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language.

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times.

Types of C Loops

There are three types of loops in C language that are as given below :

  1. do while
  2. while
  3. for

do-while loop in C

The do-while loop continues until a given condition satisfies. It is also called post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do{
        // Code to be executed
}while(condition);

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char c;
   int choice ,dummy;
   do{
       printf("Enter 1 to print Hello\nEnter 2 to print Javatpoint\nEnter 3 to Exit\n");
       scanf("%d", &choice);
       switch (choice){
           case 1:
           printf("Hello\n");
           break;
           case 2:
           printf("Javatpoint\n");
           break;
           case 3:
           exit(0);
           break;
           default:
           printf("Please enter a valid choice\n");
       }
       printf("Do you want to enter more? ");
       scanf("%d", &dummy);
       scanf("%c", &c);
   }while (c == 'y');
}

Here #include <stdlib.h> is used for the output "exit" in-built function.

Enter 1 to print Hello

Enter 2 to print Javatpoint

Enter 3 to Exit

1

Hello

Do you want to enter more? y

Enter 1 to print Hello

Enter 2 to print Javatpoint

Enter 3 to Exit

2

Javatpoint

Do you want to enter more? n

Program to print table for the given number using do while loop

#include <stdio.h>

int main()
{
   int i=1;
   int j;
   printf("Enter a number : ");
   scanf("%d", &j);
   do{
       printf("%d x %d = %d \n", j, i, i*j);
       i++;
   }while (i <= 10);
   return 0;
}

Enter a number : 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60

Infinitive do-while loop

The do-while loop will run infinitive times if we pass any non-zero value as the conditional expression, i.e. while(1);.

Comments