Input values into an array

Hello Can someone help me with this please.
This is not the full code just small aspects.

I have array

a[5] ={0};

when i try this

int i
cin >> a[i]

i get warning stating

uninitialized local variable 'i' used

if i initialise it, removes the point of input as all values would just become whatever i initialise it to be.

many thanks for any help or advice in advance
regards
bill thompson
What does a[i] actually mean? In terms of an array, it means the contents of element number i in the array a.

So, a[0] is the first element, and a[1] is the second element, and a[2] is the third element, and so on.

When you put values into an array, you need to specify which element of the array you're putting them into. Your array, a, has 5 elements. We know this because you made it like this: a[5] ={0};

So, there are five elements in your array: a[0], a[1], a[2], a[3], a[4]

How can you put a number into a[0]? Like this:

a[0] = 5;

Have you just set the value of that first element to zero? No, you set it to five. Zero is the number of the element, not the value it holds.

a[1] = 7;

Have you just set the value of that second element to 1? No, you set it to seven. One is the number of the element, not the value it holds.

cin >> a[i];

Have you just set the value of element i to i? No, we set it to whatever number came in through the cin. i is the number of the element, not the value it holds.

What happens if we never gave i a value? It could be anything. Anything at all. So which element of the array would we be putting the value into? Who knows. Could be anywhere. If i is, by chance, some number that is bigger than your array, it won't even be in your array - it'll be somewhere else completely in memory. This is why you must give i a value. To choose where in the array to put the input.
Last edited on
 
int a[5] = { 0 };

creates an array of five elements and initializes only the first element to 0. If you want all five to be set, use

 
int a[5] = { 0, 0, 0, 0, 0 };

or a loop.
@bbgst int a[5] = {0}; as well as simply int a[5] = {}; initialize all five elements to zero.
Last edited on
Topic archived. No new replies allowed.