The do-while Loop

In this tutorial, we will focus on the last type of loop construct available in C programming language which is the do-while loop. Let’s dive in.


Introduction

The do-while loop is a post-tested loop, which means the loop condition is checked after executing the loop body. When the requirement is to execute a block of code at least once before checking the condition, then the do-while loop comes in handy.


The Syntax

The actual syntax of the do-while loop is as follows:

do statement while (condition);

As we know we can always replace a single statement with a compound statement, so the following syntax of the do-while loop is also valid:

do {
    // statement(s) to repeat
} while (condition);

Notice the semicolon after the closing parentheses of the condition. It is mandatory to add this semicolon, otherwise the compiler will generate an error.

As checking the condition is the last thing in the do-while loop, the statement(s) within the loop will execute at least once.


Comparison with for and while

Unlike the do-while loop, for and while loops are pre-tested loops–they check their conditions before executing the loop body. The for loop is used when the number of iterations is known in advance and the while loop is used usually when the number of iterations is not known in advance– meaning the execution of the loop may depend upon user input. 


The Flow of Execution

Consider the following example to understand the flow of execution of the do-while loop:

#include<stdio.h>

int main()
{
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 10);
    return 0;
}

The flow of execution is as follows:

  1. Variable i is initialized to 1. 
  2. The do is encountered, and it allows us to enter into the loop body. 
  3. Value of i is printed. 
  4. Variable i is incremented.
  5. The condition is checked. 
  6. Steps 3 to 5 are repeated until the condition becomes false. 

The output of the above program is

1 2 3 4 5 6 7 8 9 10

Usage

The do-while loop is useful in situations when a set of statements needs to be executed even before the loop condition is checked. The following example demonstrates the need of the do-while loop:

Program with the while loop:

#include<stdio.h>

int main()
{
    int n, sum = 0;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    sum += n;
    
    while (n != 0) {
        printf("Enter the number: ");
        scanf("%d", &n);
        sum += n;
    }
    
    printf("Sum is %d", sum);
    return 0;
}

Output: 

Enter the number: 1
Enter the number: 2
Enter the number: 3
Enter the number: 4
Enter the number: 5
Enter the number: 0
Sum is 15

The program keeps asking the user for a number until they finally enter zero. With each iteration, the current number is added to the old sum. As soon as the user enters zero, the loop terminates and the printf() function gets evaluated which prints the sum of all numbers entered by the user. 

You might have observed that the following statements are repeated within the while loop:

printf("Enter the number: ");
scanf("%d", &n);
sum += n;

Before the while loop, it is important to write the above statements so that there will be some value in the variable n before checking the while condition.


Common Mistakes to Avoid

  • Forgetting to use the semicolon after the while statement can lead to a syntax error. 
  • Ensure that the loop will terminate after performing the desired operation. Incorrect condition or increment/decrement may lead to infinite loop.
  • Be mindful of where the loop variables are declared. If they are declared within the loop, then they are not accessible outside the loop.

Best Practices and Tips

  • Use do-while loops when the loop body needs to be executed at least once. 
  • Keep the loop condition simple to improve the readability of your code.
  • Always initialize loop variables to avoid unexpected behavior.

Level-Up Your Understanding

Question 1:  What happens if you accidentally use a comma instead of a semicolon after the while condition?

Answer:  The program will produce an error. A comma can never be used as a terminator of the statement.

Question 2:  How would you convert a for loop to its equivalent do-while loop?

Answer:  Following are the steps you can follow to convert a for loop to its equivalent do-while loop:

  1. Initialize any loop control variables before the loop.
  2. Move the loop body into the do-while loop.
  3. Ensure the loop condition of the do-while loop is equivalent to the termination condition of the for loop.
  4. Update any loop control variables within the loop body.

Consider the following example for better clarity:

#include <stdio.h>

int main() {
    // For loop
    printf("The for loop output:\n");
    for (int i = 0; i <= 5; i++) {
        printf("%d ", i);
    }
    
    // Equivalent do-while loop
    printf("\n\nThe do-while loop output:\n");
    int i;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    
    return 0;
}

Output:

The for loop output:
0 1 2 3 4 5 

The do-while loop output:
0 1 2 3 4 5 

Question 3:  Can a do-while loop have multiple conditions? Give a simple example to demonstrate the use case.

Answer:  Yes. A do-while loop can have multiple conditions just like for and while loops. We can check multiple conditions using the logical operators like && (AND operator) and || (OR operator) depending upon the requirements. Consider the following example:

#include<stdio.h>

int main()
{
    int a = 1, b = 10;
    
    do {
        printf("a = %d and b = %d\n", a, b);
        a++;
        b--;
    } while (a <= 10 && b > 0);
    
    return 0;
}

Output:

a = 1 and b = 10
a = 2 and b = 9
a = 3 and b = 8
a = 4 and b = 7
a = 5 and b = 6
a = 6 and b = 5
a = 7 and b = 4
a = 8 and b = 3
a = 9 and b = 2
a = 10 and b = 1

In the above program, two conditions a <= 10 and b > 0 are checked each time the loop runs. Only when both the conditions are true, the loop will continue to run.

Question 4:  Is it always possible to convert a while loop to a do-while loop?

Answer:  No. It is not always possible to convert a while loop to a do-while loop because in some cases, in case of while loop, the loop condition may not be true in the first iteration itself, but in do-while loop, the loop body will execute at least once. Consider the following examples for more clarity:

Example 1:  The while loop implementation

#include<stdio.h>

int main()
{
    int count = 5;
    
    while (count < 5) {
        printf("%d", count);
        count++;
    } 
    
    return 0;
}

Output:

No Output

Example 2:  The do-while equivalent

#include<stdio.h>

int main()
{
    int count = 5;
    
    do {
        printf("%d", count);
        count++;
    } while (count < 5);
    
    return 0;
}

Output:

5

So, the difference is clearly observable. In some cases, it is not possible to convert a while loop to a do-while loop without changing the logic of the program.

Question 5:  Can you write the program to find the factorial of a number using the do-while loop?

Answer:  The factorial program using the do-while loop is as follows:

#include<stdio.h>

int main()
{
    int n, i = 1; 
    unsigned long long factorial = 1; //to hold large values.
    
    printf("Enter an integer: ");
    scanf("%d", &n);
    
    if (n < 0) { // only positive numbers are allowed.
        printf("Invalid input!");
    } else {
        // Main logic
        do {
            factorial *= i;
            i++;
        } while (i <= n);
        
        printf("Factorial of %d is %llu", n, factorial);
    }
    
    return 0;
}

Conclusion

The do-while loop is useful when the loop body needs to be executed at least once. Having this loop in your arsenal is a good thing because there can be situations when a set of statements need to be executed at least once. 



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.