0
Why is this array 2 and not 3
What is the output of this code? int arr[ ] = new int[3]; for (int i = 0; i < 3; i++) { arr[i] = i; } int res = arr[0] + arr[2]; System.out.println(res); 4 I know that Array starts with 0 and if i put 0 in the for loop, its gonna be 0 + 1= 1 and 0 + 3 = 4. The solve is 4 but it comes 2, because they say its 0 + 2 = 2. I dont get it why is array [0] = 0
3 Answers
+ 2
In the first iteration i is 0, so you get arr[0] = 0. In the second iteration i is 1, so you get arr[1] = 1. On the third iteration i is 2, so you get arr[2] = 2.
+ 1
for (int i = 0; i<3; i++){
arr[i] = i;
}
firstly know that arr[0] or arr has the same address of the first bit of the arr array called as base address.
and `=` means assignment means put what is at the R.H.S. of `=` inside what is at L.H.S. of it.
initially counter i= 0, execution => arr[i] means arr shifted over i number of indexes or memory locations of type int.
So now, arr[i] = i; meaning assign value of i (which is 0 at the moment of this iteration) to the array arr shifted over i memory locations means 0 memory locations means base address meaning at the very first index/place of the array. and whenever an iteration ends meaning when the loop encounters no statement left to be executed it will increase the counter i by 1 as i++; and start from next iteration for value of i which is 1 at the moment of next iteration and as in i < 3 defines thay this loop will iterate three times for the value of i = 0, 1, 2 and will terminate finally. In programming, numbers starts from 0 and not 1.
+ 1
if an array has size 3, means it has 3 elements whose indexes starts from base address of thr array which is array arr[0] means arr shifted over 0 memory locations, arr[1], arr[2]. the index last element of an array of size n is (n-1). and if the index of an array's last element is n then the size of that array should be (n+1).