Write a program that asks the user for up to 10 integers (it could be fewer); stop prompting when the user enters zero. Then list the numbers in reverse order. Use the following example run as a guide:
Enter a number (0 to stop): 11
Enter a number (0 to stop): 33
Enter a number (0 to stop): 55
Enter a number (0 to stop): 77
Enter a number (0 to stop): 99
Enter a number (0 to stop): 0
Your numbers in reverse order are:
99, 77, 55, 33, 11
below is my current code and can't seem to figure out what i'm doing wrong.
#include <iostream>
#include <string>
using namespace std;
int main( ) {
int max = 10;
int num = 1;
int userVal[max];
int i = 0;
while(num <= max) {
cout << "Enter a number (0 to stop): ";
cin >> userVal[i];
cout << userVal[i] << endl;
if(userVal[i] == 0) {
break;
}
++num;
}
cout << num << endl;
cout << "Your numbers in reverse order are: " << endl;
for(i = num; i >= 0; --i) {
cout << userVal[i];
if(i < num - 2) {
cout << ", ";
}
}
return 0;
}
below is the output i'm getting obviously as stated above i want to numbers to print in reverse
Enter a number (0 to stop): 11
Enter a number (0 to stop): 33
Enter a number (0 to stop): 55
Enter a number (0 to stop): 77
Enter a number (0 to stop): 99
Enter a number (0 to stop): 0
6
Your numbers in reverse order are:
6553532600-6638791760, 4197268, 0, 0,
First, in your while loop, you are using i to assign the values in the array, you need num instead. Second, num should be set to zero so that the first element of the array is filled. Try this code:
#include <iostream>
#include <string>
using namespace std;
int main( ) {
int max = 10;
int num = 0;
int userVal[max];
int i = 0;
while(num <= max) {
cout << "Enter a number (0 to stop): ";
int number;
cin >> number;
cout << number << endl;
if(number == 0) {
break;
}
userVal[num] = number;
++num;
}
cout << num << endl;
cout << "Your numbers in reverse order are: " << endl;
for(i = num; i >= 0; --i) {
cout << userVal[i];
if(i < num - 2) {
cout << ", ";
}
}
return 0;
}