×

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples.

Do-While Loop:

The do-while loop constitutes a specific style of looping construct in C++ with an assured execution of the loop body at least a single time, irrespective of any condition. This occurs because the body of the loop executes prior to the verification of the condition.

Syntax:

It has the following syntax:

do {

// Loop body: Code to be executed

} while (condition);

Working:

  • The loop runs the code inside the do block first.
  • Once the while statement has been run, its condition is examined.
  • If the condition evaluates to true, the loop is repeated.
  • If the condition is false, the loop ends.

Key Features:

Several key features of the do-while loop in C++ are as follows:

1. Execution confirmed at Least Once:

Because the loop’s execution comes before the condition is verified, the do-while loop guarantees that the loop body gets run at least once, even if the condition is initially false.

2. Post-Test Loop Organization:

In contrast to the while and for loops, which verify the condition prior to the loop body being executed, the do-while loop verifies the condition after it has been executed. For activities like menu-driven programs and user input validation, this makes it helpful.

3. Adaptable and Easy to Use:

The do-while loop works well in situations like games, menus, and authentication systems where the user must interact with the application before criteria are checked. Improved control over loops in terms of execution can also be done with break and continue statements.

Algorithm:

The algorithm describes the step-by-step execution of a do-while loop:

  • Start
  • Execute the loop body (statements inside the do block).
  • Check the condition in the while statement.
  • If true, go back to Step 2 and repeat the loop.
  • If false, exit the loop.
  • End

Pseudo Code:

BEGIN

Initialize loop variable (e.g., i ← 1)

DO

Execute statements inside the loop

Update loop variable (e.g., i ← i + 1)

WHILE (condition is TRUE)

END

Example 1:

Let us take an example to illustrate the do-while loop in C++.

#include <iostream>

using namespace std;

int main() {

int i = 1;

do {

cout << "Iteration: " << i << endl;

i++;

} while (i <= 5); // Condition to continue looping

return 0;

}

Output:

Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

Explanation:

This function executes the loop body at least once even if the condition is false. This is helpful when the loop must run at least once before confirming the condition. The while condition is assessed after the loop body has been run.

Pseudo code for above code:

BEGIN

SET i ← 1

DO

PRINT "Iteration: ", i

INCREMENT i by 1

WHILE (i ≤ 5)

END

Explanation:

  • The loop does not check the condition before beginning to execute.
  • It first prints i’s value before increasing it.
  • At the conclusion, the condition is verified; if i ≤ 5, the loop is repeated.
  • The loop ends when i equals six.

Example 2:

This example illustrates how to utilize a do-while loop in a number-guessing game. The user must guess a randomly selected number between 1 and 10.

#include <iostream>

#include <cstdlib> // For rand() and srand()

#include <ctime> // For time()

using namespace std;

int main() {

int secretNumber, userGuess;

// Seed random number generator

srand(time(0));

secretNumber = rand() % 10 + 1; // Generate a number between 1 and 10

cout << "Guess a number between 1 and 10!" << endl;

do {

cout << "Enter your guess: ";

cin >> userGuess;

if (userGuess < secretNumber)

cout << "Too low! Try again." << endl;

else if (userGuess > secretNumber)

cout << "Too high! Try again." << endl;

} while (userGuess != secretNumber); // Loop until the guess is correct

cout << "Congratulations! You guessed the correct number." << endl;

return 0;

}

Output:

Guess a number between 1 and 10!

Enter your guess: 5

Too high! Try again.

Enter your guess: 3

Too low! Try again.

Enter your guess: 4

Congratulations! You guessed the correct number.

Explanation:

  • It generates a random number between 1 and 10.
  • A guess is entered by the user.
  • If the guess is too low, the computer compares it and provides a higher guess.
  • If it is too high, a lower guess is prompted.
  • The cycle is continued until the user guesses the correct number.
  • If the user guesses correctly, the application displays a success message and breaks the loop.

Conclusion:

In conclusion, the do-while loop is a useful looping construct in C++. It validates the condition after executing the loop body at least once. Therefore, it is particularly effective in scenarios where user input validation, a menu-driven system, or repeat processes must finish at least once before evaluation. The do-while loop will allow the execution of code even if the condition is initially false unlike the while and for loops. Such versatility makes this construct quite applicable to number guessing games, menus that have to be navigated, and input validation checks. When the previously mentioned method is used correctly, it can be written to create interesting applications.

Frequently Asked Questions’s:

1. What distinguishes a do-while loop from a while loop?

Whereas a while loop examines the condition first and might not run at all, a do-while loop runs at least once before checking the condition.

2. Under what circumstances is a do-while loop better than a while or for loop?

When the body of the loop needs to run at least once, like in menu-driven applications or user input validation, a do-while loop is better.

3. Can a do-while loop go infinitely?

Yes, the do-while loop runs endlessly if the loop condition never turns false. If not managed correctly, this could result in an infinite loop.

4. Does a semicolon (;) need to come after the while statement?

In actuality, in order to indicate the end point of the loop statement in a do-while loop, a semicolon (;) must come after the while(condition);.

5. Can you utilize break and continue statements with a do-while loop?

While break immediately ends the loop, continue bypasses the remainder of the current iteration’s code and checks the condition for the subsequent one.


Related Topics

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.