int array[]={0,2,4,6,8,10};
what is the value of array[array[2]];
?
Its showing ans is 8
We tried for this question,but not getting why answer is 8
int array[]={0,2,4,6,8,10};
what is the value of array[array[2]];
?
Its showing ans is 8
We tried for this question,but not getting why answer is 8
To understand the it, need some array and indexing foundation.
For example:
int array[]={0,2,4,6,8,10};
means
a[0] = 0, a1 = 2, a[2] = 4 and so on.
The C/C++ array index start from 0, and indexes are valid upto 0..length-1
So, array[2] --> 4
, the third element of the array.
Then, array[array[2]]
-->array[4]
-->8, which is the fifth element of the array.
Please check the following source for more information: C++ Array reference
int array[]={0,2,4,6,8,10};
You have declared an int array of six integer values.It will be stored as :
array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6
array[4] = 8
array[5] = 10
array[array[2]] in this line you are trying to retrieve the value of the array of index array[2](which gives you 4 as array[2] = 4 ). It will be like array[4] which gives you 8.
a simple answer will be to understand how this line is evaluated first when you declare:
int array[]={0,2,4,6,8,10};
you get:
array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6
array[4] = 8
array[5] = 10
now when you try and evaluate array[array[2]]
:
the statment array[2]
is evaluated first to 4
then the array[4]
is evaluate and it evaluates to 8
array[array[2]] --> array[ ( array[2] = 4 ) ] --> array[ 4 ] --> 8
hope this clears it up a bit
According to this array:
array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6
array[4] = 8
array[5] = 10
you want to get value for : array[array[2]]
so 1st get what is inside: array[2]
array[2] : 4
so array[array[2]] --> array[4]
therefor value is : 8
Ok , since it is here considered a multi-dimensional array (which means an array within an array) therefore, you need to find the element corresponding to the index of the inner array then afterwards the value would be actually the index of the outer array.
For example:
int array1[]: {1,2,3,4,5,6,7,8,9,10}
int array[array1[3]]
The output of the following would be : First get the value of the inner array which would be: 4 Afterwards, this would be the index number of the outer array which will correspond to value within the array which will be: 5 .