do-while Loop With Example

 do-while Loop

The do-while is an iterative control in C++ language. This loop executes one or more statements while the given condition is true. The condition in this loop is checked after the body of loop. That is why, it is executed at least once.

do-while Loop With Example

Syntax:

The syntax of do-while loop is as follows:

do

{

statement 1;

statement 2;

-------------

statement N;

} while (condition);

do 

It is the keyword that indicate the beginning of the loop.

statement

It represents the body of the loop. If the body of loop contains more than one statement, they are written in curly braces { }.

while(condition)

 It indicates the last statement of do...while loop. The condition is given as a relational expression. The statement is executed again if the condition is true. It ends with a semicolon.

Working of do-while Loop

The body of loop is executed first. The condition is evaluated after executing the statements in loop body. The control again enters the body of the loop and executes all statements in the body if the condition is true. 

This process continues as long as the condition remains true The loop terminates when the condition becomes false The loop executes at least once even if the condition is false in the beginning

while loop

do-while loop

It is pre-tested loop as the condition is checked before the body of the loop.

It is post-test loop as condition is checked after the body of the loop.

The loop body is never executed if the condition is false in the beginning.

The loop body is executed at least once even if condition is false.

The semicolon is not used after the condition.

The semicolon is used after the condition.

It is called entry controlled loop.

It is called exit controlled loop.

Write a program that inputs two numbers from the user and displays their product. It then asks the user to continue again or not. The program inputs two numbers again if the user enters 'y' and exits if the user enter 'n'.

include <iostream.h>

#include <conio.h>

void main()

{

int a, b, c,

char op;

clrscr();

do

{

cout<<"Enter two numbers";

cin > a >>b;

cout<<"Product of the numbers = "<<a*b<<endl;

cout<<"Do you want to continue? (y / n)”;

cin>>op;

}

while(op != 'n');

cout<<"Press any key to exit”;

getch();

}

Output:

Enter two numbers. 25

Product of the numbers - 10

Do you want to continue? (y / n) y

Enter two numbers: 37

Product of the numbers: 21

Do you want to continue? (y / n) n

Press any key to exit.

Post a Comment

0 Comments