OneBite.Dev - Coding blog in a bite size

Implement A Two Nested Loop In C++

Code snippet for how to Implement A Two Nested Loop In C++ with sample and detail explanation

Programming is a fundamental asset in the current digital world. Among the programming languages, C++ is widely used because of its power and flexibility. This article will help you understand and implement a two nested loop in C++.

Code snippet for Two Nested Loop in C++

For demonstrating this, we will use a simple example - printing a rectangle:

#include <iostream>
using namespace std;

int main() {
    int rows = 4;
    int columns = 5;

    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            cout  << "* ";
        }
        cout << endl;
    }

    return 0;
}

In this code, we created a 4x5 rectangle using two nested loops.

Code Explanation for Two Nested Loop in C++

The code starts by including the iostream library, which will help us with inputs and outputs in our program. The using namespace std; line is used to avoid writing std:: before cout, cin, and endl functions.

The main function starts here.

We start by declaring two integer variables rows and columns and initialize them to 4 and 5, respectively.

For(int i = 0; i < rows; i++) is the outer loop, which controls the row’s number. It starts from i=0 and runs until i is less than rows (4 in this case).

Then comes the nested loop for(int j = 0; j < columns; j++). This inner loop controls the columns. It runs from j=0 and runs until j is less than columns (5 here).

In each iteration of the inner loop, a * is printed. When the inner loop finishes executing (i.e., j equals columns), cout << endl; commands the cursor to go to the next line, thereby finishing one entire row of * of the rectangle.

As the outer loop continues, it repeats the inner loop for the specified number of rows. Finally, when the outer loop completes its cycle (i.e., i equals rows), the main() function returns 0, signaling a successful execution.

This is how a two nested loop is implemented in C++. You can adjust the rows and columns values to any value to customize the rectangle’s size as per your requirements.

c-plus-plus