C++ nested loopings - Loop within loop

Now that we have trained the concept of loopings enough, learning how to do it, let's learn another important concept, that of nested loops, or loops within loops.

Nested C++ Repetition Structures

Take a look at the previous tutorials, where we used famous exercises to fix our knowledge of repeating structures, specifically, the DO WHILE loop codes:

We put a FOR loop inside the DO WHILE loop.
That is, there is a larger loop, a parent loop, the DO WHILE, which will be repeating a base structure.

Within each iteration of this, a FOR loop is executed.
This inside loop is nested with the outside loop.

Can you see and understand its function, why does it work?
It's quite simple, but it's a very powerful technique.

Using C++ Nested Loopings

Let's use the technique of nested repetition structures to print an N x N board, that is, N rows and N columns. Here's an example of a 3x3 board to play tic-tac-toe:
- - -
- - -
- - -

The key here is to use a loop for the rows and another, internal to the first, to take care of the columns in each row.

The first FOR goes from 1 to N, is responsible for the lines.
Note that at the end of it there is a line break to print the next iteration on the bottom line.

Within the line FOR, let's print N dashes.

See how our code looks:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int lin, col, N;

    cout<<"Board size N x N: ";
    cin >> N;

    for(lin=1 ; lin<=N ; lin++){
        for(col=1 ; col<=N ; col++)
            cout<<" - ";

        cout <<endl;
    }

    return 0;
}

How to use nested loopings in C++

Let's create a program to print the following table from the image:

C++ tutorial online and free PDF download

See what a beautiful table, what a charming table, what a well-made table.
Let's learn how to do it?

First, note two two, it has:

  • 4 lines
  • 4 columns

Let's use two loops, one to take care of the rows and one to take care of the columns.

To control these loops, we will use the variables lin and col, as well as a variable num that will receive the numbers from 1 to 16,.

Let's start by working on the lines:
    for (lin = 1; lin <= 4; lin++) {
        // something
        cout << endl;
    }

Note that at the end of each iteration, we have to break a line to get to the bottom line.
Within each iteration of this, we need to print the columns, which are 4 per row.

So let's use another nested loop:
    for (lin = 1; lin <= 4; lin ++) {
        for (col = 1; col <= 4; col ++) {
            // something
        }
        cout << endl;
    }

Within that is nested, we will print the numbers.
Since the col variable ranges from 1 to 4, it prints four numbers on each line.

Let's use the num variable, initially with a value of 1, to print these values.
After the internal iteration, we have to increment this variable.

To make the table look pretty and formatted, let's use the setw command to set it to 4 spacing (you need to include the iomanip library to use this command).

See how our code looked:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int lin, col, num=1;

    for(lin=1 ; lin<=4 ; lin++){
        for(col=1 ; col<=4 ; col++){
            cout<<setw(4) << num;
            num++;
        }
        cout <<endl;
    }

    return 0;
}
Cool, isn't?

Using Nested Loops Example

Let's now print an asterisk triangle, the size you want.
For example, a triangle of size 5:
*
**
***
****
*****

Note that it will have 5 lines.
In the first row there is 1 column.
In the second row there are 2 columns.
...
In the fifth column there are 5 columns.

The first FOR, the lin control variable goes from 1 to N, where N is the size of the triangle the user wants.
Within each FOR, we will use another FOR to print the asterisks. They must print from 1 to lin, can you get this idea?

On the first line, print 1 asterisk.
On the second line, print 2 asterisks.
...
On the Nth line prints N asterisks.

See how our code looks:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int lin, col, N;

    cout<<"Triangle size: ";
    cin >> N;

    for(lin=1 ; lin<=N ; lin++){
        for(col=1 ; col<=lin ; col++)
            cout<<"*";

        cout <<endl;
    }

    return 0;
}
Note that the outside FOR uses braces, as it has more than one command line below it.
The inside FOR doesn't have to, because it only has one command line.

Be careful not to confuse the braces! Always make a correct spacing and indentation, so as not to err.

Loop inside loop inside loop...

Ok, we already saw how to nest repetition structures, we put one FOR inside another.
How about now putting one more FOR, nested with the other two?

Let's show all possible clock times during the day in the format:
hour: min: sec

That is, it goes from: 00:00:00
Until: 23:59:59

Let's use three variables: h, m and s
h goes from 0 to 23, m and s go from 0 to 59, as they represent the minutes and seconds.

Our code looks like this:
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    cout.fill('0');
    for(int h=0 ; h < 24 ; h++)
        for(int m=0 ; m < 60 ; m++)
            for(int s=0; s<60 ; s++){
                cout<<setw(2)<<h<<":";
                cout<<setw(2)<<m<<":";
                cout<<setw(2)<<s<<endl;
            }

    return 0;
}
We use setw(2) to set 2 spacing characters.
When there is nothing to appear in this spacing, 0 will appear because we use cout.fill ('0')

No comments:

Post a Comment