Reputation: 241
How can I write this same code with the while loop instead of the for loop?
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = n; j >= i; j--) {
cout << j;
}
cout << endl;
}
This is my attempt, but it does not achieve the same affect. I'm not sure why.
int n;
cin >> n;
int i = 1;
int j = n;
while (i <= n) {
while (j >= i) {
cout << j;
j--;
}
i++;
cout << endl;
}
Upvotes: 1
Views: 57
Reputation: 5416
You have to reset j
before the while(j >= i)
loop.
while (i <= n) {
j = n; //<<<<<<<< Reset j to the starting value
while (j >= i) {
cout << j;
j--;
}
i++;
cout << endl;
}
Upvotes: 1