Arrays | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
+ 1

# Arrays

What does the following mean: a. int arr[] = new int[3] (Setting the elements in the array to 3??) b. arr[i] = i; QUIZ QUESTION I'M STUCK ON 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);

17th Apr 2019, 6:46 PM
Rahim S
2 ответов
+ 2
I'll try to explain it res = 0 + 2 => 2 ( because arr[0] = 0 and arr[2] = 2). In a. there's an array initialization with length 3. In b. it's setting the values of the elements in the array. You didn't mention the initial value of the variable res ( I suppose it's 0, if it is other you just need to add it to 2).
17th Apr 2019, 7:14 PM
TheWh¡teCat 🇧🇬
+ 2
int arr[] = new int[3] - create a new array which can contain 3 integers arr[i] = i - all arrays start at the 0 index - the loop basically populates the values of the array with the value of i This is what happens with the loop: 1st iteration - i = 0 therefore arr[0]=0 Increment i -> i = 1 2nd iteration - i = 1 therefore arr[1]=1 Increment i -> i = 2 3rd iteration - i = 2 therefore arr[2]=2 Increment i -> i = 3 4th iteration - i = 3 -> loop stops because of condition i < 3 which is now false arr[0]=0 arr[2]=2 *value of res was not initialized, maybe equal to 0? int res = arr[0] + arr[1]; res = 2
17th Apr 2019, 7:24 PM
Lambda_Driver
Актуальное сегодня
Help!