Java Im working with array for loops and I cant figure out w
Java: I\'m working with array for loops and I can\'t figure out why index 5 equals 0. Why is it 3/1 = 0 +1 = 1? Whey aren\'t we using the the 6 from index 4 to plug in?
Here\'s the exercise:
What elements do the array list contain after the following code is excecuted?
int[] list = {2, 18, 6, -4, 5, 1};
for (int i = 0; i < list.length; i++){
lsit[i] = list[i] + (list[i] / list[0]);
}
Answer: [3, 24, 8, -5, 6, 1]
Solution
int[] list = {2, 18, 6, -4, 5, 1}; //This array is of size 6.
for (int i = 0; i < list.length; i++){ //This loop runs for values from i = 0, to 5.
list[i] = list[i] + (list[i] / list[0]);
//So, the steps here are:
//list[0] = list[0] + (list[0] / list[0]) = 2 + (2 / 2) = 2 + 1 = 3.
//list[1] = list[1] + (list[1] / list[0]) = 18 + (18 / 3) = 18 + 6 = 24.
//list[2] = list[2] + (list[2] / list[0]) = 6 + (6 / 3) = 6 + 2 = 8.
//list[3] = list[3] + (list[3] / list[0]) = -4 + (-4 / 3) = -4 - 1 = -5.
//list[4] = list[4] + (list[4] / list[0]) = 5 + (5 / 3) = 5 + 1 = 6.
//list[5] = list[5] + (list[5] / list[0]) = 1 + (1 / 3) = 1 + 0 = 1.
//So, the list after the modification is: {3, 24, 8, -5, 6, 1}
