×

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

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 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.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.