C++ Nested Loops
Loops are one of the fundamental concepts in programming. In C++, loops allow a program to execute a set of statements multiple times. Nested loops are simply loops inside other loops. This article will explain what nested loops are, their types, and how to use them in C++ with sample code.
A nested loop is a loop within another loop. The inner loop runs completely every time the outer loop executes one iteration. Nested loops can be used to perform repetitive tasks with multiple levels of repetition.
For example:
Nested loops are useful for working with multi-dimensional data structures like matrices, grids, or tables.
Each type can be used depending on the task you're working on. Let's explore them in more detail with sample code.
In this example, we will use a nested for loop to print a multiplication table.
#include <iostream>
using namespace std;
int main() {
int rows = 5, cols = 5;
// Outer loop for rows
for (int i = 1; i <= rows; i++) {
// Inner loop for columns
for (int j = 1; j <= cols; j++) {
cout << i * j << "\t"; // Print multiplication result
}
cout << endl; // Move to the next line after each row
}
return 0;
}
Explanation:
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
In this example, we use a nested while loop to print a pattern of stars.
#include <iostream>
using namespace std;
int main() {
int rows = 5, i = 1, j;
// Outer while loop for rows
while (i <= rows) {
j = 1; // Inner loop counter reset
// Inner while loop for columns
while (j <= i) {
cout << "*"; // Print a star
j++; // Increment the column counter
}
cout << endl; // Move to the next line after each row
i++; // Increment the row counter
}
return 0;
}
Explanation:
while
loop iterates over the rows.while
loop prints stars (*
) corresponding to the current row number.Output:
*
**
***
****
*****
In this example, we use a do-while loop to create a simple number pyramid.
#include <iostream>
using namespace std;
int main() {
int rows = 5, i = 1, j;
// Outer do-while loop for rows
do {
j = 1; // Inner loop counter reset
// Inner do-while loop for columns
do {
cout << j << " "; // Print the column number
j++; // Increment column counter
} while (j <= i); // Inner loop condition
cout << endl; // Move to the next line after each row
i++; // Increment the row counter
} while (i <= rows); // Outer loop condition
return 0;
}
Explanation:
do-while
loop iterates over the rows.do-while
loop prints the column number on each iteration.Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Nested loops are especially useful when dealing with tasks such as:
However, nested loops can increase the time complexity of a program, so it's essential to use them efficiently. As the number of iterations increases, so does the time needed to complete the task.
Incorrect Loop Conditions:
Overloading the CPU:
Misplacing Increment or Decrement Statements: