Understanding Do-While Loops

To delve into Data Structures and Algorithms, we must have a good command over control structures and determine how code flows and behaves. One such control structure, the “do-while” loop, offers a unique way to execute a block of code repeatedly based on a specified condition.

Syntax:

do{
     // code to be executed;
}while(//condition

A do-while loop is a type of control structure that allows you to execute a block of code at least once, and then repeatedly as long as a specified condition holds true. Unlike “for” and “while” loops, which may not execute their code if the initial condition is false, a do-while loop guarantees at least one execution before evaluating the condition.

Code:

C++ Code

#include <iostream>
using namespace std;

int main() {
    int n = 5;
    int factorial = 1;

    do {
        factorial *= n;
        n--;
    } while (n > 0);

    cout << "Factorial of 5 is: " << factorial << endl;

    return 0;
}

Output: Factorial of 5 is: 120

Java Code

public class FactorialCalculator {
    public static void main(String[] args) {
        int n = 5;
        int factorial = 1;

        do {
            factorial *= n;
            n--;
        } while (n > 0);

        System.out.println("Factorial of 5 is: " + factorial);
    }
}

Output: Factorial of 5 is: 120

In this example, the loop starts by initialising `factorial` to 1 and `n` to 5. It then repeatedly multiplies `factorial` by `n` and decrements `n` until `n` becomes 0. This ensures that the loop calculates the factorial correctly.

Use Cases for Do-While Loops

Do-while loops are particularly useful in situations where you want to ensure that a block of code executes at least once, such as validating user input or processing data until a certain condition is met.

Do-While vs. While Loops

While do-while loops and while loops serve similar purposes, the key difference lies in when the condition is evaluated. In a do-while loop, the condition is checked after the code block execution, guaranteeing at least one execution. In a while loop, the condition is checked before the code block, meaning the code might not execute if the initial condition is false.

Code:

C++ Code

#include <iostream>
using namespace std;

int main() {
    int i = 5;

    do {
        cout << "This is a do-while loop iteration." << endl;
        i--;
    } while (i < 0);

    return 0;
}

Output: This is a do-while loop iteration.

Java Code

public class DoWhileExample {
    public static void main(String[] args) {
        int i = 5;

        do {
            System.out.println("This is a do-while loop iteration.");
            i--;
        } while (i < 0);
    }
}

Output: This is a do-while loop iteration.

In this code, the condition of i < 0 is not satisfied but still one iteration of the do-while operation will not take place. After its code block execution, the condition is checked and then the do-while block exits. This example illustrates the behaviour of the do-while loop when the condition is not satisfied initially.

Code:

C++ Code

#include <iostream>
using namespace std;

int main() {
    int i = 5;

    while (i < 0) {
        cout << "This is a while loop iteration." << endl;
        i--;
    }

    return 0;
}

Java Code

#include <iostream>
using namespace std;

int main() {
    int i = 5;

    while (i < 0) {
        cout << "This is a while loop iteration." << endl;
        i--;
    }

    return 0;
}

The while loop checks the condition before executing the code block. The initial condition (i < 0) is false as 5 is > 0, and the code block does not execute at all.

Converting a For Loop to a Do While Loop

Converting a for loop into a while loop involves a straightforward transformation of the syntax. The key changes include moving the initialization outside the loop, placing the condition in the while statement, and handling the increment or decrement at the end of the loop block.

For Loop Example:

C++ Syntax:

for (int i = 1; i <= 5; i++) {
    cout << i << endl;
}
Java Syntax:

for (int i = 1; i <= 5; i++) {
   System.out.println(i);
}

Equivalent Do-While Loop:

C++ Syntax:

int i = 1;
    do {
        cout << i << endl;
        i++;
    } while (i <= 5);
Java Code:
do {
      System.out.println(i);
            i++;
        } while (i <= 5);

Special thanks to Gauri Tomar for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article