0
Please explain how the looping works in this program
#include<iostream> using namespace std; int main (){ for (int i=1;i<=5;i++){ for (int j=5;j>=i;j--) cout<<"*"; cout<<endl; } return 0; }
2 Respostas
0
the best way to see how the loop variables change is to print out their values inside the loop, for example
#include <iostream>
using namespace std;
int main() {
for(int i=1; i<=5; i++){
for(int j=5; j>=i; j--){
cout << i << ", " << j << endl;
}
}
return 0;
}
and analyze the output. you should notice that this is what happens:
1. i=1 (outer loop). check i<=5 (1<=5 - true). enter inner loop.
a. j=5 (inner loop). check if j>=i (5>=1); since the condition is true, we enter the loop and print '*'
b. j=4 (inner loop). again check j>=i (4>=1 - true), enter the loop and print '*'
c. j=3. repeat steps above
......
f. j=0 (inner loop). check j>=i (0>=1 - false). we exit from inner, back to outer loop.
2. i=2 (outer loop). check i<=5 (2<=5 - true). we enter the inner loop.
a. j=5 (inner loop). check j>=i (5>=2 - true). enter loop and print '*'
b. j=4. repeat steps as above.
......
e. j=1. check j>=i (1>=2 - false). back to outer loop.
3. i=3. repeat steps as above.
.......
6. i=6. check i<=5 (6<=5 - false). we exit from the whole loop.
0
thank you so much for your help