Help with Arrays?

Hello. I am new to C++ and I am having difficulty with arrays. When I ask the program to print out the array of numbers that were inputted, the program would always output a 0. Now, if I set the program to output the array in the for loop, it will work out fine. Can someone explain this to me as to why it does that? Also, let's say I want to use the numbers inputted for something else (maybe use it in another function or algorithm, etc). Do I have to put those functions or algorithms in the for loop as well to use the inputted numbers? Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>

using namespace std;

int main ()
{
    int input;
    int count;
    int array[10];
    
    cout << "Enter 10 numbers:";
    for (count = 0; count < 10; count++)
    {
        cin >> input;
        array[count] = input;
        
       //cout << array[count] << " "; <-- Program prints out numbers inputted. 
    }
        cout << array[count] << " "; //Program prints out 0
        return 0;
}
When the control achieves this statement

cout << array[count] << " ";

count is equal to 10. So you are trying to output element array[10] that does not exist. So some arbitrary value that is in the memory outside the array is outputed.
Last edited on
Thanks! I figured out the problem now. Since what you said is true, I did this and it worked out!

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

using namespace std;

int main ()
{
    int input;
    int count;
    int array[10];
    
    cout << "Enter 10 numbers:";
    for (count = 0; count < 10; count++)
    {
        cin >> input;
        array[count] = input;
    }
    for (count = 0; count < 10; count ++)
        cout << array[count] << " ";
    
        return 0;
}
Topic archived. No new replies allowed.