The while
and do-while
loops in C++ are control structures that allow repeating the execution of a block of code as long as 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.
If you want to learn more about Loops
check the Introduction to Programming Course read more ⯈
WHILE Loop
The while
loop executes a block of code as long as 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
}
In this loop:
condition
: It is an expression that is evaluated in each iteration. If it istrue
, the block of code inside thewhile
is executed. If it isfalse
, the loop ends.- Code to execute: This is where the code to be repeated is placed.
Basic Example
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
while
loop prints the numbers from 0 to 4, since the conditioncounter < 5
istrue
as long ascounter
is less than 5.
DO-WHILE Loop
The do-while
loop is similar to the while
loop, but it guarantees that the block of code will be executed at least once. The basic syntax is as follows:
do
{
// Code to execute at least once
} while (condition);
In this loop:
- Code to execute: It is executed at least once before the condition is checked.
condition
: It is evaluated after each iteration. If it istrue
, the block of code executes again; if it isfalse
, the loop ends.
Basic Example
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 that the code executes at least once, even if
counter
starts at 5.
Differences between While and Do-While
- The
while
loop checks the condition before each iteration, while thedo-while
loop checks it after each iteration. - The
do-while
loop guarantees at least one execution of the code block, while thewhile
loop may not execute the block if the condition isfalse
from the beginning.
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++; // Increments the counter by 1
}
return 0;
}
This while
loop executes while counter
is less than or equal to 10, printing each value of counter
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; // Adds the entered number to the 'sum' variable
std::cout << "Enter another positive number (a negative number to end): ";
std::cin >> number;
}
std::cout << "The total sum of the positive numbers is: " << sum << std::endl;
return 0;
}
This while
loop executes 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; // Marks that the number has been found
std::cout << "Number " << searched << " found at position " << index << std::endl;
}
index++; // Increments 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 it is not found, it indicates that it is not in the list.
Confirm Program Continuation
In this example, a do-while
loop is used to ask the user to enter “y” or “n” to confirm whether 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 finished." << std::endl;
return 0;
}
This do-while
loop asks the user to enter “y” or “n”. The block of code executes at least once and then repeats while the response is not “y” or “n”.
These examples are intended to show how to use the While loop. It does not mean that it is the best way to solve the problem they address.