I'm having a small issue for a partially filled array. Between the cout and last for loop, it outputs extra garbage. It does everything else I want it to, it's just that extra bit, just a string of random numbers. The output I'm getting looks something like this:
1 2 3 4 5 6 7
You entered:
1979085795
7
3
4
2
100
Could you please explain to me what it's doing? Is there something I've missed? Thank you so much for any help. Here's the code for the program:
#include <iostream>
usingnamespace std;
//This program prompts a user for an integer x.
//Make the program output x numbers in reverse.
//You may safely assume that x is not larger than 20.
int main()
{
int numbers[20]; //Array with 20 elements
int userinput; //Collect x number of integers from user
cout << "How many numbers?" << endl;
cin >> userinput;
for (int counter = 0; counter < userinput; counter++)
{
cout << "Enter number " << counter << endl;
cin >> numbers[counter];
}
cout << "You entered: " << endl;
for(int x = userinput; x >= 0; --x)
{
cout << numbers[x] << endl;
}
}
Remember, arrays start at zero, and end with userinput MINUS 1, so, you are accessing a value outside what you specified in userinput. Try for(int x = userinput - 1; x >= 0; --x) for line 24, instead.
Also, you should make sure that the userinput value is not negative, or above 20, or whatever value you may set your numbers array at, at a later date.