Loops in C++: for, while, do-while

Loops in C++: for, while, do-while

Loops in the C++ programming language are user-defined custom control features or repeating block structures that allow a block of program code to be repeated multiple times based on a user-defined manual custom logic condition expression in a C++ program. The most commonly used loops in C++ programs are the for, while, and do-while basic structure loop methods.

Loops in C++: for, while, do-while

The most common loops used in C++ programming are.

  • for loop
  • while loop
  • do-while loop

Remember, each loop used in the C++ programming language has its own unique syntax and use method.

Detail explanation of for, while, and do-while loops in c++

Loop Featurefor loop methodwhile loop methoddo-while loop method
Initial Condition checkFor loop check condition Before the loop starts (pre-check) action performWhile loop check condition Before each iteration (pre-check) action performsDo-while loop check condition After each iteration (post-check) method used
Success or guaranteed?For loop start Only if the condition is true at start pointIt starts Only when if the condition is true at start pointHere it Always executes at least once time in program body
Best apply caseUsed it When you know the number of iterations step in program or you want to print fix number seriesYou can use it When the number of iterations step process is unknown, but you need to check the condition in first initial phaseIt provides you to guarantee at least one time loop iteration method, regardless of the condition is false
Syntax or use flexibilityUsed it when you want More concise, and when loop initialization and update process are simpleWhile loop is Simple and flexible to use, but you need to set condition must be set before loop startsDo while loop Always executes once before checking the actual condition

So, let’s explore for, while, and do-while in C++ programming in detail.

For Loop Concept in C++.

The for loop is commonly used in C++ programs when the C++ user knows in advance the number of statement repetitions (iteration values) in a program. A for loop primarily consists of three elements. The initialization step is where the loop is started, the condition or logic step is where a user-defined condition is analyzed or tested, and finally, the increment/decrement step is where a variable’s value is updated according to the condition logic. A block of loop code is executed until a user-defined manual condition becomes true.

For Loop Syntax in C++.

for (initialization; condition; increment/decrement) {

// Here you write the code to execute.

}

For Loop syntax explanation.

  • Initialization – This sets the parameter starting point in a for loop, typically initializing a variable’s value.
  • Condition – Here you can test the for loop with a particular condition expression. This runs the program as long as the user-defined manual condition remains true.
  • Increment/Decrement – After each loop iteration step, the initialized loop variable is updated with a new value. This can be ++, –, increment or decrement, or any other operator or expression.

For Loop Example in C++.

#include <iostream>

using namespace std;

int main() {

// Here the for loop prints numbers from 1 to 10

for (int p = 1; p <= 10; p++) {

cout << p << ” “;

}

return 0;

}

For Loop program explanation.

  • In this example, the for loop is initialized with the value p = 1 and continues in the current program as long as the condition p <= 10 is defined as true. Here, after each for loop iteration, the value of the variable p is updated or incremented by 1.

While Loop Concept in C++.

When you want to repeat a block of program source code a particular number of times until a user-defined expression condition is true in a C++ program, you can use a while loop in your program. In this, the user-defined custom condition is checked or analyzed before the execution of each loop value iteration. If the user-defined custom condition in the while loop is false at the beginning, then the while loop body is not executed.

While Loop Syntax in C++.

while (condition) {

// Here you write your program code to be executed.

}

While Loop Element Explanation.

  • In a while loop, the program executes a block of code based on a number of user-defined conditions as long as the user-defined condition is true.

While Loop Example in C++.

#include <iostream>

using namespace std;

int main() {

int p = 1;

/ here it prints numbers from 1 to 11 using a while loop method

while (p <= 11) {

cout << p << ” “;

p++; // here it increments p to avoid an infinite loop situation

}

return 0;

}

While Loop program explanation.

  • In this example, the while loop checks before each value iteration whether the user-defined condition p <= 11 is true or not. If the user-defined condition is true, it executes. So, it prints the current value of the variable p, and displays the value of the variable p incremented by 1.
  • If no condition in the while loop is ever false, then the while loop in the current program will continue running forever (infinite loop). For example, if the value of the variable p is never increased here, then the loop will continue running infinitely.

Do-while Loop Concept in C++.

A do-while loop in a C++ program follows the same syntax and methods as a while loop. A unique feature of a do-while loop is that a user-defined condition is checked or analyzed after the loop body is executed. A do-while loop guarantees that the do-while loop will execute at least once, even if the first analyzed condition is defined as false.

Syntax of a do-while loop in C++.

do {

// Here you write your program code to be executed.

} while (condition);

do-while Element Explanation.

  • A do-while loop executes code once in a program, then checks or analyzes a user-defined condition. If the user-defined condition is true, the current program code is executed again. Here, in a do-while loop, the process continues to run until a user-defined do-while loop condition finally becomes false.

Example of a do-while loop in C++.

#include <iostream>

using namespace std;

int main() {

int p = 1;

// Here it prints numbers from 1 to 11 using a do-while loop situation

do {

cout << p << ” “;

p++; // Here it increments the p parameter value to avoid an infinite loop situation

} while (p <= 11);

return 0;

}

do-while Loop program explanation.

  • A do-while loop in a C++ program guarantees that the do-while loop will execute at least once in the program body, regardless of the starting value of the p variable. Then, it tests or analyzes whether the condition p <= 11 is true or not before proceeding to the next step with the second loop iteration step.

Using a for loop to add numbers.

C++ users can use a for loop in a program to add a set of integer number values ​​multiple times and display their total added value.

Example of using a for loop to add integer numbers.

#include <iostream>

using namespace std;

int main() {

int total = 0;

// Here we use a for loop for the total integer numbers from 1 to 7

for (int p = 1; p <= 7; p++) {

total += p; // Here it adds the p variable to the total number

}

cout << “Here is the total from 1 to 7. The number is – ” << total << endl;

return 0;

}

Explanation of using a for loop to add integer numbers.

  • Here, the for loop adds integer numbers from 1 to 7 multiple times, and each time a value is added, the program adds the value of the variable p to the variable value total to get the total.

Using a while loop for user input.

When you want to keep prompting a user for input in a C++ program until a valid user input value is entered, we use a while loop.

Example of a while loop for user input.

#include <iostream>

using namespace std;

int main() {

int integer;

// here it asks the user to enter an integer number between 1 and 1000

cout << “Please enter a number between 1 and 1000 – “;

cin >> integer;

// Here it asks you to enter an integer number valid in the below range

while (integer < 1 || integer > 1000) {

cout << “Invalid integer value input, please enter an integer number between 1 and 1000.”;

cin >> integer;

}

cout << “Your entered number is valid in the range 1 to 1000 – ” << integer << endl;

return 0;

}

Explanation of a while loop for user input.

  • In this example, the while loop keeps accepting integer value input from the user until the user input value falls between the integer value range of 1 and 1000.

Using a do-while loop to select a menu.

A do-while loop is used in C++ programs when C++ users want to display menu information and perform a manual action based on the user’s choice selection.

Example of using a do-while loop to select a menu.

#include <iostream>

using namespace std;

int main() {

int selection;

do {

cout << “==== Course Menu ====\n”;

cout << “1. Nielit O Level \n”;

cout << “2. Nielit A Level \n”;

cout << “3. FullStack Development \n”;

cout << “4. MernStack Development \n”;

cout << “5. Exit Course Menu \n \n”;

cout << “Enter your course choice = “;

cin >> selection;

switch (selection) {

case 1:

cout << “\n Your selection course is Nielit O Level \n \n”;

break;

case 2:

cout << “\n Your selection course is Nielit A Level \n \n”;

break;

case 3:

cout << “\n Your selection course is FullStack Development \n \n”;

break;

case 4:

cout << “\n Your selection course is MernStack Development \n \n”;

break;

case 5:

cout << “Exiting Course…\n \n”;

break;

default:

cout << “Invalid course selection, please try again.\n”;

}

} while (selection != 5); //here it Exits when user selects 5

return 0;

}

Explanation of a do-while loop to select a menu.

  • The do-while loop in this program ensures that the course menu is displayed at least once for user choice selection, and continues to allow the user to make the correct choice until they select option 5 to exit the course menu.

Leave a Reply