Partially Filled Arrays help

Hello everyone. New user here, first post.

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:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include <iostream>
using namespace 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;
    }
}
@Duders

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.
Last edited on
@whitenite1

That did it! Excellent.

Also, added a while loop for if userinput < 0 or > 20 upon your suggestion. Thank you. :)
@Duders..

You're very welcome.
Topic archived. No new replies allowed.