How does this for loop work?

closed account (4wRjE3v7)
Hi I am new to programming and in my class we wrote this code, but I am not sure how it did what it did! :( Can someone explain this to me? Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    int num;
    
    cout<<"Please enter a positive integer: ";
    cin>>num;
    
    for(int i=1; i<=num; i++)
    {
        for(int j=1; j<=num; j++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
}



sample output:

Please enter a positive integer: 2
**
**
for the first for loop.
for example let us enter 2 for num.
for(int i=1; i<=num; i++)
you are checking the num if that num is <= i. you will go through the next loop
for(int j=1; j<=num; j++)
and will check if j less than or = to num will go throgh the loop until j become bigger than num. so, we will go through the second loop two times. once we finish we go back to the first loopfor(int i=1; i<=num; i++) and the i will become 2 which is true for our condition. then we will go through the second loop again for the second time and will print the star two times. then back to the first loop. Now the i is = 3 which is false which our loop going to terminate.

Topic archived. No new replies allowed.