Home | Computer | do-while loop in C++ | Difference between while and do-while loop

do-while loop in C++ | Difference between while and do-while loop

August 24, 2022

do-while is an iterative control in C++ language. A do-while loop in C++ is a type of looping structure that repeats a block of code while a condition remains true. In programming languages, the do-while loop is often used to repeat some action until a certain condition becomes false.

A do-while loop is similar to a while loop, except that it does not have a break statement at its end. Instead, it continues repeating the block of code until the condition becomes false.

Syntax of do-while loop

do

{

Statement 1;

Statement 2;

.

.

Statement N;

}

while (condition)

do:    It is the keyword that indicates the beginning of the loop.

Condition:  The condition is given as a relational expression. The statement is executed only if the given condition is true. If the condition is false, the statement is never executed.

Statement:    Statement is the instruction that’s executed when the condition is true. Two or further statements are written in braces{}. It’s called the body of the loop.

Working of do-while loop

First of all, the body of the loop is executed. After executing the statement in the loop body the condition is evaluated. If it is true, the control again enters the body of the loop and executes all statements in the body again. This process continues as long as the condition remains true. The loop terminates when the condition becomes false.

This loop is executed at least once even if the condition is false in the beginning.

Flowchart of do-while loop

image showing the flowchart of do-while loop

Example

#include <iostream.h>

#include <conio.h>

Void main()

{

int a, b, c, r;

clrscr ()Ø›

Cout<< ” Enter the first number: “;

cin>>a;

Cout<< ” Enter the second number: “;

cin>>b;

c = 1;

r = 1;

do

{

r = r * a;

c = c + 1;

}

While (c<=b);

cout<<“Result is”<<r;

getch();

}

Output

Enter first number: 2

Enter the second number: 3

Result is 8

Difference between while loop and do-while loop

While loopdo-while loop
In a while loop, the condition comes before the body of the loop.In a do-while loop, the condition comes after the body of the loop.
If the condition is false in the beginning while the loop is never executed.do-while is executed at least once even if the condition is false in the beginning.