The do while loop in C

do… while loop #

Syntax:

do{
// body of do while loop
    statement 1;
   statement 2;
}while(condition);

In do while first the statements in the body are executed then the condition is checked. If the condition is true then once again statements in the body of do while are executed. This process keeps repeating until the condition becomes false. As usual, if the body if do while loop contains only one statement, then braces ({}) can be omitted. Notice that unlike while loop, in do while a semicolon(;) is placed after the condition.

The do while loop differs significantly from while loop because in do while loop statements in the body are executed at least once even if the condition is false. In the case of while loop condition is checked first before executing statements in the body of the loop.

The following program print numbers between 1 and 100 which are multiple of 3 using the do while loop.

#include<stdio.h> // include the stdio.h

int main()
{
    int i = 1; // declare and initialize i to 1

    do
    {
        // check whether i is multiple of 3 not or not
        if(i % 3 == 0)
        {
            printf("%d ", i); // print the value of i
        }
        i++; // increment i by 1
    }while(i < 100); // stop the loop when becomes greater than 100

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 7
5 78 81 84 87 90 93 96 99

How it works:

In line 6, we have declared and initialized variable i. Then the control comes inside the body of the do while loop. Inside the body of the loop the if condition (i%3==0) is tested, if it is true, then the statement inside the if block i is executed. i++ is used to increment the value. At last, the do while condition (i<100) is checked. If it is true then statements inside the body of the loop are executed once again. This process keeps repeating as long as the value of i is less than 100.

Where should I use do while loop ? #

Most of the time you will use while loop instead of do while. However, there are some scenarios in where do while loop suits best. Consider the following problem.

Let's say you want to create a program to find the factorial of a number. As you probably know factorial is only valid for 0 and positive numbers. Here is one way you can approach this problem.

Let's say a user entered a negative number, so instead of displaying an error message and existing the program, a better approach would be to ask the user again to enter a number. You have to keep asking until the user enters a positive number. Once a positive number is entered, calculate factorial and display the result.

Let's see how we can implement it using while and do while loop.

Using while loop #

#include<stdio.h> // include the stdio.h

int main()
{
    int num;
    char num_ok = 0;

    // keep asking for numbers until num_ok == 0
    while(num_ok==0)
    {
        printf("Enter a number: ");
        scanf("%d", &num);

        // if num >= 0 set num_ok = 1 and stop asking for input
        if(num>=0)
        {
            num_ok = 1;
        }
    }

   // calculate factorial
}

Using do while #

#include<stdio.h> // include the stdio.h

int main()
{
    int num;

    do
    {
        printf("Enter a number: ");
        scanf("%d", &num);
    }while(num<0); // keep asking for numbers until num < 0

   // calculate factorial
}

Notice that solution using while loop is more involved, to achieve the same thing we have to create an extra variable num_ok, and an additional if statement. On the other hand. do while loop achieve the same thing without any trickery and it's more elegant and concise.

Before we leave do while loop, let’s take one more example.

The Following program program calculates the Simple interest.

/******************************************
* Program to find the Simple interest *
******************************************/

#include<stdio.h> // include stdio.h

int main()
{
    float p, r, t;
    char ch = 'y';

    do
    {
        printf("Enter principal: ");
        scanf("%f", &p);

        printf("Enter rate: ");
        scanf("%f", &r);

        printf("Enter t: ");
        scanf("%f", &t);

        printf("SI = %.2f", (p *r * t)/100 );

        printf("\n\nCalculate SI one more time ? ('Y' for Yes, 'n' for no ) : ");
        scanf(" %c", &ch); // notice the preceding white space before %c character
    }while(ch == 'y'); // stop asking for numbers once 0 is entered

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

Enter principal: 15000
Enter rate: 4.5
Enter t: 3
SI = 2025.00

Calculate SI one more time ? ('Y' for Yes, 'n' for no ) : y
Enter principal: 20000
Enter rate: 5.4
Enter t: 4
SI = 4320.00

Calculate SI one more time ? ('Y' for Yes, 'n' for no ) : n

Exiting ....
122