#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
return 0;
}Loops in C++: Repeating Instructions With Different Loop Constructs
Direct Answer & Core Concept
Writing the same instructions again and again would make your program longer and harder to maintain.
C++ solves this problem with loops.
Loops allow you to execute a block of code repeatedly as long as a specified condition is satisfied. Instead of writing the same instruction multiple times, you can write it once and let the loop handle the repetition.
C++ provides three traditional loop constructs: for, while, and do-while. It also provides the range-based for loop, which makes working with arrays and collections easier.
Detailed Explanation & Mechanics
What Are Loops in C++?
A loop in C++ is a control structure that repeatedly executes a block of statements while a condition is satisfied.
Loops are useful when you need to perform the same task multiple times without writing the same code repeatedly.
For example, if you want to print numbers from 1 to 5, you can use a for loop.
Example: A Simple Loop in C++
Output:
1
2
3
4
5In this example:
int i = 1initializes the loop variable.i <= 5checks whether the loop should continue.i++increases the variable by one after each iteration.coutdisplays the current value.
The loop repeats until the condition becomes false.
Why Are Loops Used in C++?
Loops make programming easier because they reduce repeated code and help automate tasks.
Some common uses of loops include:
Printing numbers in a sequence.
Calculating the sum of multiple numbers.
Displaying multiplication tables.
Processing arrays and collections.
Reading multiple user inputs.
Searching for specific values.
Repeating menu options in an application.
Performing calculations on large amounts of data.
For example, if you want to print the multiplication table of 5, you can use a loop instead of writing ten separate output statements.
Types of Loops in C++
C++ supports different loop constructs depending on how you want to control repetition.
The main types are:
forloopwhileloopdo-whileloopRange-based
forloop
The first three are traditional loop constructs. The range-based for loop is a convenient modern C++ feature for iterating over arrays and other ranges.
Let's understand each one with examples.
1. for Loop in C++
A for loop is used when you know how many times you want to repeat a block of code.
It is commonly used for counting operations, printing number sequences, processing arrays, and performing calculations.
Syntax of for Loop
for (initialization; condition; update) {
// Code to execute repeatedly
}A for loop has three main parts:
| Part | Purpose | Example |
|---|---|---|
| Initialization | Sets the starting value | int i = 1 |
| Condition | Checks whether the loop continues | i <= 5 |
| Update | Changes the loop variable | i++ |
How Does a for Loop Work?
Suppose you write:
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}The loop follows these steps:
The variable
istarts at 1.C++ checks whether
i <= 5.If the condition is true, the loop body executes.
The value of
iincreases by one.The condition is checked again.
The loop stops when the condition becomes false.
Example 1: Print Numbers From 1 to 10
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
cout << i << endl;
}
return 0;
}Output:
1
2
3
4
5
6
7
8
9
10Example 2: Print Even Numbers Using for Loop
#include <iostream>
using namespace std;
int main() {
for (int i = 2; i <= 20; i += 2) {
cout << i << " ";
}
return 0;
}Output:
2 4 6 8 10 12 14 16 18 20Here, the variable increases by 2 during every iteration, so only even numbers are printed.
Example 3: Calculate the Sum of Numbers From 1 to 10
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
cout << "Total Sum: " << sum;
return 0;
}Output:
Total Sum: 55The loop adds each number to the sum variable.
Example 4: Multiplication Table Using for Loop
#include <iostream>
using namespace std;
int main() {
int number = 5;
for (int i = 1; i <= 10; i++) {
cout << number << " x " << i
<< " = " << number * i << endl;
}
return 0;
}Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50When Should You Use a for Loop?
Use a for loop when:
You know the number of iterations.
You want to count numbers.
You need to process an array using an index.
You want to calculate totals.
You need to repeat an operation a fixed number of times.
2. while Loop in C++
A while loop repeatedly executes a block of code as long as its condition remains true.
It is useful when you do not know in advance how many times a loop needs to run.
Unlike a for loop, initialization and updating are usually written separately.
Syntax of while Loop
while (condition) {
// Code to execute repeatedly
}The condition is checked before each iteration. If it is false initially, the loop body does not execute.
Example 1: Print Numbers From 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << endl;
i++;
}
return 0;
}Output:
1
2
3
4
5Explanation
First, the variable
iis initialized to 1.The
whileloop checks whetheri <= 5.If the condition is true, the number is displayed.
The variable increases by one.
The process repeats until the condition becomes false.
Example 2: Calculate the Sum Using while Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
int sum = 0;
while (i <= 10) {
sum += i;
i++;
}
cout << "Total Sum: " << sum;
return 0;
}Output:
Total Sum: 55Example 3: Reverse Counting Using while Loop
#include <iostream>
using namespace std;
int main() {
int i = 10;
while (i >= 1) {
cout << i << endl;
i--;
}
return 0;
}Output:
10
9
8
7
6
5
4
3
2
1Example 4: Read User Input Until Zero Is Entered
A while loop is particularly useful when the number of inputs is not known in advance.
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number (0 to stop): ";
cin >> number;
while (number != 0) {
cout << "You entered: " << number << endl;
cout << "Enter another number (0 to stop): ";
cin >> number;
}
cout << "Loop finished.";
return 0;
}Sample Input:
10
20
30
0Output:
You entered: 10
You entered: 20
You entered: 30
Loop finished.This program continues accepting numbers until the user enters zero.
When Should You Use a while Loop?
Use a while loop when:
The number of iterations is unknown.
Repetition depends on user input.
You need to wait for a condition to change.
You are processing data until a particular value is reached.
You want to repeat an operation while a condition remains true.
3. do-while Loop in C++
A do-while loop is similar to a while loop, but it checks the condition after executing the loop body.
This means the statements inside a do-while loop execute at least once, even if the condition is false initially.
It is useful when an operation must happen before checking whether repetition is required.
Syntax of do-while Loop
do {
// Code to execute
} while (condition);Important: A do-while loop requires a semicolon after the closing condition.
Example 1: Print Numbers From 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << endl;
i++;
} while (i <= 5);
return 0;
}Output:
1
2
3
4
5Explanation
The loop starts executing the code inside
do.The current value of
iis displayed.The variable is increased by one.
The condition
i <= 5is checked.If the condition is true, the loop repeats.
If the condition is false, the loop terminates.
Example 2: do-while Executes at Least Once
This is one of the most important differences between while and do-while.
#include <iostream>
using namespace std;
int main() {
int i = 10;
do {
cout << "Hello C++";
i++;
} while (i <= 5);
return 0;
}Output:
Hello C++Even though the condition is false initially, the loop body executes once before checking the condition.
Example 3: Simple Menu Using do-while Loop
A menu-driven program is a common practical application of the do-while loop.
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "\n===== MENU =====" << endl;
cout << "1. Home" << endl;
cout << "2. About" << endl;
cout << "3. Contact" << endl;
cout << "0. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Welcome Home!" << endl;
break;
case 2:
cout << "About Us Page" << endl;
break;
case 3:
cout << "Contact Page" << endl;
break;
case 0:
cout << "Exiting Program..." << endl;
break;
default:
cout << "Invalid Choice!" << endl;
}
} while (choice != 0);
return 0;
}Sample Output:
===== MENU =====
1. Home
2. About
3. Contact
0. Exit
Enter your choice: 1
Welcome Home!
===== MENU =====
1. Home
2. About
3. Contact
0. Exit
Enter your choice: 0
Exiting Program...The menu appears at least once and continues until the user selects option 0.
When Should You Use a do-while Loop?
Use a do-while loop when:
The code must execute at least once.
You are creating menu-driven applications.
You need to ask users to enter information before checking a condition.
You want to repeat an operation after its first execution.
You are building simple interactive programs.
4. Range-Based for Loop in C++
C++11 introduced the range-based for loop.
It provides a simpler way to iterate over elements of arrays, containers, and other suitable ranges without manually managing an index variable.
This loop is particularly useful when you want to access every element in a collection.
Syntax of Range-Based for Loop
for (data_type variable : collection) {
// Use the current element
}Here:
data_typespecifies the type of each element.variablerepresents the current element.collectionis an array, container, or suitable range.
Example 1: Using Range-Based for Loop With an Array
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int number : numbers) {
cout << number << endl;
}
return 0;
}Output:
10
20
30
40
50Explanation
The loop automatically visits each element of the numbers array.
You do not need to declare an index variable or manually check the array length.
Example 2: Calculate the Sum of Array Elements
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum += number;
}
cout << "Total Sum: " << sum;
return 0;
}Output:
Total Sum: 150Example 3: Modify Array Elements Using References
A range-based loop normally copies each element into its loop variable.
If you want to modify the original elements, use a reference with &.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int &number : numbers) {
number *= 2;
}
for (int number : numbers) {
cout << number << " ";
}
return 0;
}Output:
2 4 6 8 10The reference allows the loop to modify the original array elements.
When Should You Use a Range-Based for Loop?
Use a range-based for loop when:
You want to visit every element in an array.
You are processing elements in a vector or another container.
You do not need the element index.
You want simpler and more readable iteration code.
You want to modify elements using references.
Difference Between for, while, do-while, and Range-Based for Loops
Each loop construct serves a different purpose.
| Feature | for | while | do-while | Range-based for |
|---|---|---|---|---|
| Condition checked | Before each iteration | Before each iteration | After each iteration | Automatically iterates over a range |
| Minimum executions | Zero | Zero | One | Zero if range is empty |
| Best use | Known iteration count | Condition-based repetition | At least one execution | Visiting collection elements |
| Manual index | Usually used | Usually used | Usually used | Not required |
| Update | Usually in loop header | Usually inside loop body | Usually inside loop body | Automatic iteration |
Which Loop Should You Choose?
Use
forwhen the number of repetitions is known.Use
whilewhen repetition depends on a condition.Use
do-whilewhen the code must execute at least once.Use range-based
forwhen you want to visit each element in a collection.
There is no single loop that is best for every situation. Choose the one that makes your program easiest to understand.
Nested Loops in C++
A nested loop is a loop placed inside another loop.
The outer loop controls the overall repetition, while the inner loop executes completely for each iteration of the outer loop.
Nested loops are commonly used for patterns, tables, matrices, and multidimensional arrays.
Example 1: Simple Nested for Loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << " " << j << endl;
}
}
return 0;
}Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3Explanation
The outer loop runs three times.
For every outer iteration, the inner loop also runs three times.
Therefore, the inner loop executes a total of nine times.
Example 2: Print a Star Pattern Using Nested Loops
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}Output:
*
* *
* * *
* * * *
* * * * *The outer loop controls the rows, while the inner loop prints the stars in each row.
Example 3: Multiplication Table Using Nested Loops
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "\t";
}
cout << endl;
}
return 0;
}Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15Infinite Loops in C++
An infinite loop is a loop that continues executing because its termination condition never becomes false.
Infinite loops can be intentional in some applications, such as servers, event-processing systems, and continuously running programs.
However, an accidental infinite loop can cause a program to consume unnecessary processing time.
Example 1: Infinite for Loop
#include <iostream>
using namespace std;
int main() {
for (;;) {
cout << "Running..." << endl;
}
return 0;
}The for loop has no initialization, condition, or update expression. Since there is no condition that becomes false, it continues indefinitely unless something terminates it.
Example 2: Infinite while Loop
#include <iostream>
using namespace std;
int main() {
while (true) {
cout << "Hello C++" << endl;
}
return 0;
}The condition is always true, so the loop never ends on its own.
How to Stop an Infinite Loop
You can use a break statement when a specific condition is met.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (true) {
if (i > 5) {
break;
}
cout << i << endl;
i++;
}
return 0;
}Output:
1
2
3
4
5The loop terminates when i becomes greater than 5.
Using break and continue Inside Loops
The break and continue statements are useful when you need additional control over loop execution.
Using break
The break statement immediately terminates the nearest enclosing loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
cout << i << " ";
}
return 0;
}Output:
1 2 3 4 5Using continue
The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
cout << i << " ";
}
return 0;
}Output:
1 3 5 7 9This program skips even numbers and prints only odd numbers.
Loop Control Flow in C++
Understanding how a loop executes will make it easier to write correct programs.
Flow of a for Loop
A for loop generally follows this sequence:
Initialization takes place once.
The condition is checked.
If true, the loop body executes.
The update expression executes.
The condition is checked again.
The loop ends when the condition becomes false.
Flow of a while Loop
A while loop follows this sequence:
The condition is checked.
If true, the loop body executes.
The loop body updates the required variables.
The condition is checked again.
The loop terminates when the condition becomes false.
Flow of a do-while Loop
A do-while loop follows this sequence:
The loop body executes.
The condition is checked.
If true, the loop repeats.
If false, the loop terminates.
The main difference is that a do-while loop checks its condition after executing the loop body.
Complete C++ Program Using Different Loops
Let's combine different loop constructs in one practical program.
C++ Code
#include <iostream>
using namespace std;
int main() {
// For loop
cout << "For Loop:" << endl;
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl << endl;
// While loop
cout << "While Loop:" << endl;
int j = 1;
while (j <= 5) {
cout << j << " ";
j++;
}
cout << endl << endl;
// Do-while loop
cout << "Do-While Loop:" << endl;
int k = 1;
do {
cout << k << " ";
k++;
} while (k <= 5);
cout << endl << endl;
// Range-based for loop
cout << "Range-Based For Loop:" << endl;
int numbers[] = {10, 20, 30, 40, 50};
for (int number : numbers) {
cout << number << " ";
}
return 0;
}Output
For Loop:
1 2 3 4 5
While Loop:
1 2 3 4 5
Do-While Loop:
1 2 3 4 5
Range-Based For Loop:
10 20 30 40 50Explanation
This program demonstrates four different loop constructs:
The
forloop prints numbers using initialization, condition, and update.The
whileloop repeats while its condition is true.The
do-whileloop executes its body before checking the condition.The range-based
forloop visits every element in an array.
Although the syntax is different, all four constructs help reduce repeated code.
Common Mistakes When Using Loops in C++
Beginners often make mistakes when writing loops. These mistakes can cause unexpected output, infinite loops, or programs that do not work as expected.
1. Forgetting to Update the Loop Variable
Incorrect:
int i = 1;
while (i <= 5) {
cout << i << endl;
}The variable i is never increased, so the condition remains true.
Correct:
int i = 1;
while (i <= 5) {
cout << i << endl;
i++;
}2. Using the Wrong Loop Condition
Incorrect:
for (int i = 1; i < 5; i++) {
cout << i << endl;
}This prints numbers only from 1 to 4.
If you want to include 5, use:
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}3. Adding an Extra Semicolon After a Loop
Incorrect:
for (int i = 1; i <= 5; i++);
{
cout << "Hello";
}The semicolon creates an empty loop body. The block that follows is separate and executes only once.
Correct:
for (int i = 1; i <= 5; i++) {
cout << "Hello" << endl;
}4. Forgetting the Semicolon in a do-while Loop
Incorrect:
do {
cout << "Hello";
} while (true)Correct:
do {
cout << "Hello";
} while (false);A do-while statement must end with a semicolon.
5. Creating an Accidental Infinite Loop
Always make sure that the loop condition can eventually become false, or that the loop has a suitable exit mechanism.
6. Using continue Incorrectly in a while Loop
Make sure that the loop variable is updated even when a continue statement executes.
Otherwise, the loop may never reach its termination condition.
7. Using the Wrong Starting Value
Always check the initialization value, especially when working with arrays and indexes.
For an array containing five elements, valid indexes are generally 0 to 4.
Best Practices for Writing Loops in C++
Follow these practices to write cleaner and more reliable C++ programs:
Choose the loop construct that best matches the task.
Use
forloops when the number of iterations is known.Use
whileloops for condition-based repetition.Use
do-whilewhen the code must execute at least once.Use range-based
forloops to process collection elements.Always check loop conditions carefully.
Update loop variables correctly.
Avoid accidental infinite loops.
Use meaningful variable names.
Keep nested loops as simple as possible.
Use braces to make loop bodies clear.
Use
breakandcontinueonly when they improve readability.
Frequently Asked Questions About Loops in C++
1. What is a loop in C++?
A loop in C++ is a control structure that repeatedly executes a block of code while a specified condition is satisfied.
2. How many types of loops are there in C++?
C++ has three traditional loop constructs: for, while, and do-while. It also supports the range-based for loop, which is commonly used with arrays and containers.
3. What is a for loop in C++?
A for loop is used to repeat a block of code when the initialization, condition, and update can conveniently be managed in one loop header.
4. What is a while loop in C++?
A while loop repeatedly executes a block of code as long as its condition remains true. The condition is checked before each iteration.
5. What is a do-while loop in C++?
A do-while loop executes the loop body first and checks its condition afterward. Therefore, its body executes at least once.
6. What is the difference between while and do-while loops?
A while loop checks the condition before executing the loop body. A do-while loop checks the condition after executing the body.
7. What is a nested loop in C++?
A nested loop is a loop placed inside another loop. It is commonly used for patterns, tables, matrices, and multidimensional arrays.
8. What is an infinite loop in C++?
An infinite loop is a loop that continues running because its termination condition never becomes false or because it has no terminating condition.
9. Can a for loop run without a condition?
Yes. If the condition is omitted from a for loop, it is treated as true. The loop continues until a jump statement or another mechanism terminates it.
10. What is a range-based for loop in C++?
A range-based for loop is a C++ feature that allows you to visit each element in an array, container, or other suitable range without manually managing an index.
11. Can we use break inside a while loop?
Yes. The break statement can terminate a while loop immediately.
12. What is the use of continue in C++ loops?
The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.
13. Which loop executes at least once in C++?
The do-while loop executes at least once because its condition is checked after the loop body.
14. Which loop is best for beginners in C++?
The for loop is often a good starting point for counting tasks because initialization, condition, and update are written together. However, the best loop depends on the problem.
15. Can loops be nested in C++?
Yes. You can place one loop inside another loop. Nested loops are useful for working with rows and columns, patterns, and multidimensional data.
Runnable Code Example: Loops in C++
C++20 / C++23#include <iostream>
#include <vector>
int main() {
// 1. Classic for loop
std::cout << "For loop: ";
for (int i = 1; i <= 3; ++i) {
std::cout << i << " ";
}
std::cout << "
";
// 2. while loop
int count = 3;
std::cout << "While loop: ";
while (count > 0) {
std::cout << count << " ";
count--;
}
std::cout << "
";
// 3. do-while loop (guaranteed at least one run)
int value = 0;
std::cout << "Do-While loop: ";
do {
std::cout << value << " ";
value++;
} while (value < 1);
std::cout << "
";
// 4. Range-based for loop (Modern C++)
std::vector<std::string> nodes = {"alpha", "beta", "gamma"};
std::cout << "Range-based for: ";
for (const auto& node : nodes) {
std::cout << "[" << node << "] ";
}
std::cout << "
";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: How does a range-based for loop work under the hood?
Q: Why should you use const auto& in range-based for loops?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
for (const auto& item : container) when inspecting collections.2. Use
for (auto& item : container) when modifying elements in place.3. Ensure loop termination conditions are reachable to prevent infinite execution.