Well...I am not sure if this is the mistake the author makes before the book is published or I just misinterpret it. Anyway, here is the example of the very simple program:
Code:
#include <iostream>
using namespace std;
int main() {
int i, n;
// Get a number from the keyboard and initialize i.
cout << "Enter a number and press Enter: ";
cin >> n;
i = 1;
while (i <= 1){ // While i less than or equal to n,
cout << i << " "; // Print i
i = i + 1; // Add 1 to i.
}
return 0;
}
And then here comes the question for the exercise
2.2.2 Alter the example so it prints all the numbers from n to 1 in reverse order. For example: 5 4 3 2 1. (Hint: to decrement a value inside the loop use the statement i = i - 1.
I get stuck here. I was unable to print n to 1 with the use of i = i - 1. Maybe because of my low level math skills. This is my code:
Code:
#include <iostream>
using namespace std;
int main()
{
// Declare two variables as n and i
int n, i;
// Assign 5 to i and 1 to n and do the calculation
n = 1;
i = 5;
while(i >= n){
cout << i << " ";
i = i - 1;
}
return 0;
}
I can't have the cout print n to 1, only can I have cout print i. But if I wanna print n, I cannot use i = i - 1 expression. Is it a mistake of the exercise or I misinterpret it? I dunno how I can print i with the use of i = i - 1. It seems impossible to me.