OverIQ.com

The do while loop in C

Last updated on July 27, 2020


do… while loop #

Syntax:

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

In do while loop 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 are executed. This process keeps repeating until the condition becomes false. As usual, if the body of do while loop contains only one statement, then braces ({}) can be omitted. Notice that unlike the while loop, in do while a semicolon(;) is placed after the condition.

The do while loop differs significantly from the 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 the condition is checked first and if it true only then the statements in the body of the loop are executed.

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#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 i becomes greater than 100

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

Expected Output:

1
2
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 5, 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 is executed. The statement i++ increments the value of i by 1. 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 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 that factorial is only valid for 0 and positive numbers. Here is one way you can approach this problem.

Let's say the user entered a negative number, so instead of displaying an error message and quitting 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 or 0. Once a positive number or 0 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 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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 loop #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#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 the 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, the do while loop achieves 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 calculates Simple interest:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/******************************************
 Program to calculate the Simple interest 
 *
 * SI = (Principal * Rate * Time) / 100
 *
******************************************/

#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 
    }while(ch == 'y');        // keep asking for P, R and T til the input is 'y'

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

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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