Do While Loop

A do-while loop differs from a standard while loop. Unlike a while loop, a do-while loop executes the statements within the loop’s body before checking the test condition.

Even if a condition is initially false, the do-while loop will have already executed once. A do-while loop is similar to a while loop, except that the body is guaranteed to be executed at least once.

In contrast to for and while loops, which test the loop condition first and then run the code contained inside the loop body, the do-while loop examines its condition at the end of the loop.

Following is the syntax for using a do-while loop.

} while (test condition);

The body of the do-while loop is first run once. The test condition is only then evaluated. If the test condition is true, the sequence of instructions within the loop’s body is repeated, and the test condition is evaluated. The technique is repeated until the test condition becomes false. The loop is terminated if the test condition returns false.

This is one illustration of how a do-while loop works.

#include <iostream>
using namespace std;
int main()
    int i = 5;
        cout << i << " ";
    } while (i < 5);
    return 0;



Even though I was less than 5 from the start, the do-while allowed the print statement to run once before terminating.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.