Jump to content

Nested Loops in C++


Recommended Posts

In C++, when we need to repeat the code’s block, we utilize the “loops” at that place. This reduces our time for typing the same code again and again. We use the “loops” in C++ to repeat a code section. The “loops” method is a very efficient and time-saving process in C++ programming. There are different types of loops provided by the C++ language like “for loop”, “while loop”, “do-while loop”, and “nested loop”. The “nested loop” means we place two loops inside each other or we can also say that one loop contains another loop inside it.

Here, we will only explore the “nested” loops in C++ in this guide. The codes in which we utilize these “nested” loops are as follows:

Example 1:

We must include the header file while working in C++, so we include the “iostream” header file here. The header files are included so that we may utilize the methods or functions in our code that are declared in them. Underneath this, we add the “std” namespace and call the “main()” method at that place.

Then, we utilize the “for” loop in which we also place another “for” loop; it is called the “nested for loop”. In the first “for” loop, we initialize the “a” variable of the “int” data type with “1”. The condition is also placed here which says “a <= 3” and then increments “++a” in the value of “a”. We place the “cout” underneath this “for” loop to print some text here. In the next “for” loop, we initialize a “b” variable of the “int” data type with the value of “1”. The condition that we add here is “b <= 4” and it is also incremented. We place another “cout” below this “nested for”.

Code 1:

#include <iostream>
using namespace std;
int main() {
  for (int a = 1; a <= 3; ++a) {
    cout << " My for loop: " << a << endl;  
    for (int b = 1; b <= 4; ++b) {
      cout << "     My nested loop: " << b << endl;  
    }
  }
  return 0;
}

 

Output:

The result of the given “nested loop” is now rendered here. The first “cout” statement appears three times as we adjusted its condition to “3”, and the second “cout” statement appears four times as we adjusted its condition to “4” in the code.

Nested-Loops-in-C-1.png

Example 2:

The “main()” function is called. Then, we initialize the “myNewWeek” and “weekDays” variables with the values of “2” and “7”, respectively. The “nested for loop” that we use in the following is composed of two “for” loops that we position inside one another. The “i <= myNewWeek” condition and the “++i” increment in the value of of “i” are placed here in the first “for” loop where we initialize the “i” variable of the “int” data type with “1”. We position the “cout” underneath this “for” loop to print some text here. We initialize a variable called “j” of the “int” data type with the value of “1” in the following “for” loop.

Here, we add the “j <= weekDays” condition and increment it. Another “cout” is positioned beneath this “nested for” loop.

Code 2:

#include <iostream>
using namespace std;
int main() {
    int myNewWeek = 2, weekDays = 7;

    for (int i = 1; i <= myNewWeek; ++i) {
        cout << "The week is: " << i << endl;
        for (int j = 1; j <= weekDays; ++j) {
            cout << "    The day of the week is: " << j << endl;
        }
    }
    return 0;
}

 

Output:

This is how the “nested loop” that was mentioned previously is now displayed. The code now shows three instances of the first “cout” statement (whose condition is fixed to “2”) and four instances of the second “cout” statement (whose condition is fixed to “7”).

Nested-Loops-in-C-2.png

Example 3:

Here, we want to display the “@” symbol in a triangular pattern with the “nested for” loop. For this, we place the first “for” loop and adjust its condition to “i <= 6” after initializing the “int i” variable with the value of “1”.

Then, we also apply the incrementation in the value of “i”. Underneath this, we have another “for” in which we place another condition that says “j <= i” after initializing the “j” variable as the “int” with the value of “1”. The value of this “j” variable is also incremented here. Now, we add the “cout” where the “@” symbol is placed. Now, this renders the “@” symbol triangularly.

Code 3:

#include <iostream>
using namespace std;                                                                                      
int main() {                                                                                                                                      
   for (int i = 1; i <= 6; i++) {
      for (int j = 1; j <= i; j++) {
         cout << "@  ";
      }
      cout << endl;
   }

    return 0;
}

 

Output:

We get this result because of the “nested loop” that we utilized in the provided code. Here, we can see that the “@” symbol appears in a triangular pattern.

Nested-Loops-in-C-3.png

Example 4:

We want to use the “nested for” loop to show the “@” symbol in a triangle pattern. To do this, we position the first “for” loop. Then, we initialize the “int a” variable with the value of “1” and set its condition to “a <= 8”. Next, we also increase the value of “a” in this instance. Then, we have another “for” where we initialize the “b” variable as the “int” with the value of “1” with another condition that indicates “b <= a”. The value of “a” is likewise increased. The “cout” is now added where we place the “*” symbol. This now causes the console to display the “*” sign in a triangle pattern.

Code 4:

#include <iostream>
using namespace std;                                                                    
int main() {                                                                                                                                                                        
   for (int a = 1; a <= 8; a++) {
      for (int b = 1; b <= a; b++) {
         cout << "*  ";
      }
      cout << endl;
   }
    return 0;
}

 

Output:

We obtained this result by employing a “nested loop” in the aforementioned code. Here, we can observe that the “@” symbol is arranged in triangle.

Nested-Loops-in-C-4.png

Example 5:

Now, we want to render the prime number only. So, we declare the “x” and “y” variables as the “int” variables. Then, we place two “for” loops, one after the other, which are said to be the “nested for” loop. The first loop contains the condition which is “x <= 50” after initializing the “x” variable with “2”. We also perform the incrementation on the value of “x” in this loop.

Then, we have another loop where we add another condition that says “y <= (x/y)” after assigning a “2” value to the “y” variable. We also increment the value of “y” within this loop. Below this, we utilize the “if” which checks the “!(x%y)” condition. If the factor is not found here, it will not print that value as we add the “break” statement and move towards the second “if” which we add in the following. Here, it checks the condition again which is “y > (x/y)”. If it is true, it prints that value and also prints “is a prime number”.

Code 5:

#include <iostream>
using namespace std;
int main () {
   int x, y;
   for(x = 2; x <= 50; x++) {
      for(y = 2; y  (x/y)) cout << x << "  is a prime number." << endl;
   }  
   return 0;
}

 

Output:

Now, all the prime numbers are rendered here which we get after applying the “nested for” loop in our code.

Nested-Loops-in-C-5.png

Conclusion

This guide is all about the nested loops in C++ and explained that we utilize the “nested loops” whenever we want the repetition of the code’s section. We thoroughly explored this concept and learned how to utilize the “nested loops” in our codes. We demonstrated several examples in which we utilized the “nested loops” along with their explanations and rendered the outcomes of all these codes here in this guide.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...