A nested loop in c++ example that a wide range of topics, including the basics of nested loops, practical examples, and advanced use cases. Let’s dive deep into the concept of nested loops in C++, exploring different types of loops, their syntax, usage, and practical applications.
Understanding nested loop in c++ example
Nested loops in C++ are loops that run inside another loop. The “external loop” controls the number of times the “inner loop” accomplishes. Nested loops are usually used for iterating over multi-dimensional data structures like forms or operating periodic operations that include various levels of iteration.
Types of nested loop in c++ example
Before reviewing reside loops, it’s owned by learn the various types of loops in C++:
for loop a loop that runs a particular number of occasions, frequently used when the number of iterations is famous earlier.
for (initialization; condition; increment) {
// code to be executed
}
while
loop: A loop that runs as long as a specified condition is true, often used when the number of iterations is not known in advance.
while (condition) {
// code to be executed
}
do-while
loop: Similar to awhile
loop, but it guarantees at least one execution of the loop body because the condition is checked after the body is executed.
do {
// code to be executed
} while (condition);
Basic Structure of Nested Loops
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is executed, the inner loop runs completely from start to finish. The general structure of nested loops is:
for (initialization; condition; increment) { // Outer loop
}
// Code to be executed inside the outer loop after the inner loop completes
}
Example 1: Simple Multiplication Table
Let’s start with a basic example that demonstrates the use of nested for
loops to print a multiplication table:
#include <iostream>
int main() {
int rows = 5, columns = 5; // Define the number of rows and columns
// Outer loop for rows
for (int i = 1; i <= rows; ++i) {
// Inner loop for columns
for (int j = 1; j <= columns; ++j) {
std::cout << i * j << "\t"; // Print the product of i and j
}
std::cout << std::endl; // Move to the next line after each row
}
return 0;
}
Explanation:
- Outer loop (
i
): Runs from 1 to 5, representing the rows of the multiplication table. - Inner loop (
j
): Runs from 1 to 5 for each iteration of the outer loop, representing the columns. - The multiplication (
i * j
) is calculated and printed in a tabular format usingstd::cout
.
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
Example 2: Printing a Star Pattern
Nested loops can also be used to create patterns. Here’s an example that prints a right triangle of stars (*
):
#include <iostream>
int main() {
int n = 5; // Number of rows
// Outer loop for rows
for (int i = 1; i <= n; ++i) {
// Inner loop for columns
for (int j = 1; j <= i; ++j) {
std::cout << "* "; // Print star
}
std::cout << std::endl; // Move to the next line after each row
}
return 0;
}
Explanation:
- The inner loop (
j
) runs from 1 toi
, printing a number of stars equal to the current row number.
Output:
*
* *
* * *
* * * *
* * * * *
Example 3: 2D Array Traversal
Nested loops are essential when working with multi-dimensional arrays. Here’s an example that initializes and prints a 2D array (matrix):
#include <iostream>
int main() {
int matrix[3][3] = { // Initialize a 3x3 matrix
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Outer loop for rows
for (int i = 0; i < 3; ++i) {
// Inner loop for columns
for (int j = 0; j < 3; ++j) {
std::cout << matrix[i][j] << " "; // Print each element
}
std::cout << std::endl; // Move to the next line after each row
}
return 0;
}
Explanation:
- 2D Array (
matrix
): A 3×3 array is initialized with numbers from 1 to 9. - Each element of the matrix is printed in a grid format.
Output:
1 2 3
4 5 6
7 8 9
Example 4: Combining Different Types of Loops
You can nest a while
loop inside a for
loop, or vice versa. Here’s an example where a for
loop is nested inside a while
loop:
#include <iostream>
int main() {
int i = 1;
// Outer while loop
while (i <= 5) {
// Inner for loop
for (int j = 1; j <= i; ++j) {
std::cout << j << " "; // Print numbers from 1 to i
}
std::cout << std::endl; // Move to the next line after each iteration of i
++i; // Increment i
}
return 0;
}
Explanation:
- The outer
while
loop runs whilei
is less than or equal to 5. - The inner
for
loop prints numbers from 1 up toi
. - The result is a right triangle of numbers.
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Example 5: More Complex Patterns – Diamond Shape
Nested loops can also create more complex patterns, like a diamond shape:
#include <iostream>
int main() {
int n = 5; // Number of rows for the upper half
// Upper half of the diamond
for (int i = 1; i <= n; ++i) {
// Print leading spaces
for (int j = 1; j <= n - i; ++j) {
std::cout << " ";
}
// Print stars
for (int k = 1; k <= 2 * i - 1; ++k) {
std::cout << "*";
}
std::cout << std::endl; // Newline after each row
}
// Lower half of the diamond
for (int i = n - 1; i >= 1; --i) {
// Print leading spaces
for (int j = 1; j <= n - i; ++j) {
std::cout << " ";
}
// Print stars
for (int k = 1; k <= 2 * i - 1; ++k) {
std::cout << "*";
}
std::cout << std::endl; // Newline after each row
}
return 0;
}
Explanation:
- The upper half of the diamond is created by the first pair of nested loops, which prints spaces and stars in a pyramid shape.
- The lower half of the diamond is created by the second pair of nested loops, which decreases the number of stars and increases the leading spaces in each subsequent line.
Output:
*
***
*****
*******
*********
*******
*****
***
*
Example 6: Nested loop in c++ example
A nested loop in c++ example are less common but can be useful when the loop body needs to run at least once.