- #1
smilesofmiles
- 19
- 0
Hello! :-) I am having a hard time with understanding the logic behind decrementing nested for loops. The review problem I'm dealing with is below. This one makes the numbers go backwards.
When I put this to paper, the second for loop changes j to a number less than 0. I know that can't possibly be right.
So, I tried solving the problem in a different way. I thought it would help me figure out what's going on above but I still don't understand the logic. My code doesn't make the numbers go backwards. Here's what I would've done.
What am I missing? Any help or direction is greatly appreciated with a thank you in advance!
Code:
#include <iostream>
using namespace std;
int main(){
for (int i = 0; i < 5; i++){
for (int j = i; j >= 0; j--) /* What's going on here? This looks so simple but I can't figure it out. */
cout << j; // I understand that j is going down by one each time the inner loop condition is met?
cout << endl;
}
return 0;
}
When I put this to paper, the second for loop changes j to a number less than 0. I know that can't possibly be right.
So, I tried solving the problem in a different way. I thought it would help me figure out what's going on above but I still don't understand the logic. My code doesn't make the numbers go backwards. Here's what I would've done.
Code:
#include<iostream>
using namespace std;
int main (){
for (int i = 0; i < 5; i++){ //This is saying that there are up to 5 places in each row from 0.
for (int j = 0; j <= i; j++) // For each column they will print until they match each row.
cout << j; // The row will then increment by one when j <=i is satisfied.
cout << endl;
}
return 0;
}
What am I missing? Any help or direction is greatly appreciated with a thank you in advance!
Last edited: