How to decrement a value within a loop?

Hello, I'm having quite a bit of trouble with this question. I'm following along with a book and have been scratching my head trying to figure out where I'm going wrong.

The question is as follows: Alter the example so that it prints all the numbers from n to 1 in
reverse order, as in 5 4 3 2 1.

This is the original code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;

int main() {

int i = 1, n;

// Get number from the keyboard and initialize i.
cout << "Enter a number and press ENTER: ";
cin >> n;

while (i <= n) { // While i less than or equal n,
cout << i << " "; // Print i,
i = i + 1; // Add 1 to i.
}

system ("PAUSE");
return 0;
}


This is me trying to alter it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() {

int i, n;

// Get number from the keyboard and initialize i.
cout << "Enter a number and press ENTER: ";
cin >> n;

while (i <= n) { // While i less than or equal n,
cout << i << " "; // Print i,
i = i - 1; // Subtract 1 from i.
}

system ("PAUSE");
return 0;
}


I changed the 'i = i + 1" to subtract to decrement. But all it gives me is an endless loop.

I appreciate any help. and not looking for the answer, just general guidance :)
Last edited on
Of course it would, as il becomes less and less and it will never become greater than n.

just decrease and print n itself, and make condition n > 0
Feel incredibly stupid now. 'i' didn't even need to be present. Marking as solved.

Thank you very much for the help :)
Topic archived. No new replies allowed.