The while and do-while loops in C++ are control structures that allow repeating the execution of a block of code while a specific condition is met.
These loops are useful when the exact number of iterations is not known in advance and, instead, we want to repeat code under certain conditions.
Differences Between While and Do-While
- The while loop checks the condition before each iteration, while the
do-whileloop checks it after each iteration - The do-while loop guarantees at least one execution of the code block, while the
whileloop may not execute the block if the condition isfalsefrom the start
If you want to learn more, check out the Introduction to Programming Course
WHILE Loop
The while loop executes a block of code while a condition is true. The basic syntax of a while loop in C++ is as follows:
while (condition)
{
// Code to execute while the condition is true
}
- condition: An expression evaluated in each iteration. If it is
true, the code block inside thewhileis executed. If it isfalse, the loop ends. - Code to execute: Here you place the code to be repeated.
Let’s see a basic example that uses a while loop to print numbers from 0 to 4:
#include <iostream>
int main() {
int counter = 0;
while (counter < 5) {
std::cout << counter << std::endl;
counter++;
}
return 0;
}
In this example:
- The
whileloop prints numbers from 0 to 4, since the conditioncounter < 5istruewhilecounteris less than 5.
DO-WHILE Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once. The basic syntax is as follows:
do
{
// Code to execute at least once
} while (condition);
- Code to execute: Executes at least once before the condition is checked.
- Condition: Evaluated after each iteration. If it is
true, the code block executes again; if it isfalse, the loop ends.
Let’s see an example that uses a do-while loop to print numbers from 0 to 4:
#include <iostream>
int main() {
int counter = 0;
do {
std::cout << counter << std::endl;
counter++;
} while (counter < 5);
return 0;
}
In this example, the do-while loop
- Produces the same result as the previous while loop
- But guarantees the code runs at least once, even if
counterstarts at 5
Practical Examples
Count to 10
In this example, a while loop is used to count from 1 to 10 and print each number:
#include <iostream>
int main() {
int counter = 1;
while (counter <= 10) {
std::cout << counter << std::endl;
counter++; // Increment the counter by 1
}
return 0;
}
This while loop runs while counter is less than or equal to 10, printing each counter value and then incrementing it.
Sum Positive Numbers Entered by the User
In this example, a while loop is used to sum positive numbers entered by the user until a negative number is entered:
#include <iostream>
int main() {
int sum = 0;
int number;
std::cout << "Enter a positive number (a negative number to end): ";
std::cin >> number;
while (number >= 0) {
sum += number; // Add the entered number to the variable 'sum'
std::cout << "Enter another positive number (a negative number to end): ";
std::cin >> number;
}
std::cout << "The total sum of positive numbers is: " << sum << std::endl;
return 0;
}
This while loop runs while the user enters positive numbers. Each number is added to the sum variable. The loop ends when a negative number is entered.
Search for a Number in a List
In this example, a while loop is used to search for a specific number in a list of numbers:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int searched = 7;
int index = 0;
bool found = false;
while (index < numbers.size() && !found) {
if (numbers[index] == searched) {
found = true; // Mark that the number has been found
std::cout << "Number " << searched << " found at position " << index << std::endl;
}
index++; // Increment the index
}
if (!found) {
std::cout << "Number " << searched << " not found in the list" << std::endl;
}
return 0;
}
This while loop searches for a specific number in a vector. If the number is found, its position is printed; if not found, it indicates it’s not in the list.
Confirm Program Continuation
In this example, a do-while loop is used to ask the user to enter “s” or “n” to confirm if they want to continue:
#include <iostream>
#include <string>
int main() {
std::string response;
do {
std::cout << "Do you want to continue? (y/n): ";
std::cin >> response;
} while (response != "y" && response != "n");
std::cout << "Program terminated." << std::endl;
return 0;
}
This do-while loop asks the user to enter “s” or “n”. The code block executes at least once and then repeats while the answer is not “s” or “n”.
These examples are intended to show how to use the While loop. It does not mean it is the best way to solve the problem they address
