Using a loop, complete the following method so that it goes through the array from left to right, one element at a time and replaces that element with the sum of itself and the next element in the array (if there is a next element). For example, if the input is {1, 3, 5} the output must be {4, 8, 5} -- on the first iteration 1 was replaced by 1+3; on the second iteration 3 was replaced by 3+5.
public static void addNextItem(int[] arr)
{
}
public static void addNextItem(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { arr[i] += arr[i + 1]; } }
import java.util.Arrays; public class AddNextItemTest { public static void addNextItem(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { arr[i] += arr[i + 1]; } } public static void main(String[] args) { int[] arr = {1, 3, 5}; System.out.println(Arrays.toString(arr)); addNextItem(arr); System.out.println(Arrays.toString(arr)); } }
Get Answers For Free
Most questions answered within 1 hours.