CS Foundations : Nested Loops Patterns using C++ (A short guide to help you get familiar with the concept of nested loops)

CS Foundations : Nested Loops Patterns using C++ (A short guide to help you get familiar with the concept of nested loops)

Last Updated : 30 Aug, 2022 | By : Sameer Chauhan

Nested loops are often used to create patterns in the form of 2D matrix. This guide will help you understand the concept of nested loops and how to implement it to create patterns. In this guide, we will provide you with the syntax of the nested loops and solutions to some of the most asked problems requiring the concept of nested loop.

🚀So what are actually nested loops??

Well nested loops is nothing but a special arrangement of one loop inside another meant to tackle the problems of Nested Loop Patterns which are often asked in the exams and test the user's basic understanding of implementation of the concept of Nested Loops to deal with 2D Matrix manipulations.

🚀Syntax for Nested For loop

for ( initialization; condition; increment ) {

   for ( initialization; condition; increment ) {

      // statement of inside loop
   }

   // statement of outer loop
}

🚀Syntax for Nested While loop

while(condition) {

   while(condition) {

      // statement of inside loop
   }

   // statement of outer loop
}

🚀Syntax for Nested Do While loop

do{

   do{

      // statement of inside loop
   }while(condition);

   // statement of outer loop
}while(condition);

With the basics of nested loop syntax under your belt, it's time to put that knowledge to use and solve some nested loop pattern problems. In this guide, we've provided the solution to some of these problems for you to work through. The more practice you get, the better equipped you'll be to tackle similar problems on your own.

✍️Problem 1 : Print the following pattern

*
**
***
****
*****
//Solution to the problem

#include<iostream>
using namespace std;
int main()
{
    int i, j;
    for(i=1; i<=5; i++)
    {
        for(j=1; j<=i; j++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
    return 0;
}

✍️Problem 2 : Print the following pattern

*
**
***
****
*****
****
***
**
*
//Solution to the problem

#include<iostream>
using namespace std;
int main()
{
    int i, j;
    for(i=1; i<=5; i++)
    {
        for(j=1; j<=i; j++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
    for(i=4; i>=1; i--)
    {
        for(j=1; j<=i; j++)
        {
            cout<<"*";
        }
        cout<<endl;
    }  
    return 0;
}

✍️Watch this lecture to understand the concept of Nested Loop through a video

🚀Do it youself

Solve these problems to gauge your preparation level. Do let us know in the comment section if you face any doubt in understanding the concept. You can also post your problem and we will you help out with that asap!

😄Happy Learning!