0
can someone explain 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);
3 Answers
+ 9
int arr[ ] = new int[3];
// Array of integers of length 3 is declared
for (int i = 0; i < 3; i++) {
arr[i] = i;
//value of i i.e. 0, 1, 2 is assigned to array of integers i.e. arr
}
// arr[0] = 0, arr[1] = 1 and arr[2] = 2
int res = arr[0] + arr[2];
// 0 + 2 = 2, 2 is stored in res
System.out.println(res); 2 is printed in console
+ 6
@Luka š
+ 2
you create an array with a range of 3 (index : 0, 1 and 2)
then you create a loop starting from 0 and stopping on 2
(because the loop will not run when i equals 3)
everytime this loop goes, it puts the value of i inside the i-th index of the array
"arr[0] = 0, arr[1] = 1, arr[2] = 2"
then, 'res' will be the sum of the value of the first arrayindex + the value of the last
"res = 0 + 2". // equals 2
with the last line you show the result. //2