OneBite.Dev - Coding blog in a bite size

Implement A Three Nested Loop In C++

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

Loops find extensive applications in software and programming languages. Among these applications, creating nested loops or loops within loops is an essential skill for developers. In this article, we’ll understand how to implement a three nested loop in C++.

Code snippet for Three Nested Loop in C++

#include <iostream>
using namespace std;

int main() {
  for(int i=0; i<3; i++) {
    for(int j=0; j<3; j++) {
      for(int k=0; k<3; k++) {
        cout<< "Value of i = "<< i << ", j = "<< j << ", k = "<< k <<endl;
      }
    }
  }
  return 0;
}

Code Explanation for Three Nested Loop in C++

The three nested loop program in C++ provided above uses three for loops. Let’s understand the code step by step.

  1. In this code snippet, we have our main method where our execution starts. The int main() is the entry point of our program.

  2. Next, we import the iostream library using the preprocess directive #include<iostream>. This library allows us to read and write from and to the console using respectively the cin and cout streams.

  3. We have used the namespace std which mean we can use names for objects and variables from the standard library.

  4. Next, for(int i=0; i<3; i++) is our outer loop. This loop will execute three times because we’ve set the condition i<3. With each iteration, the value of ‘i’ will increase by 1.

  5. Inside the outer loop, we have another loop for(int j=0; j<3; j++). This is our first inner loop. For each single loop of ‘i’, this loop will also execute three times. So, nine times in total (3 times ‘i’ x 3 times ‘j’).

  6. Finally, the ‘k’ loop for(int k=0; k<3; k++) is nested inside the ‘j’ loop. This loop will execute three times for each single loop of ‘j’. So, twenty-seven times in total (3 times ‘i’ x 3 times ‘j’ x 3 times ‘k’).

  7. cout<< "Value of i = "<< i << ", j = "<< j << ", k = "<< k <<endl; This line prints out the values of i, j, and k with each iteration.

By implementing this three nested loop in C++, we’re effectively creating a block of code that repeats itself 27 times, each time with different values of i, j, and k. This type of structure can be used to perform repetitive tasks efficiently, making it a truly useful and versatile mechanism in programming.

c-plus-plus