numbers: An array of integers
result: A new array of integers, where 1 has been added to each number in the original array
numbers array always contains at least one number.[1, 2, 3, 4, 5][2, 3, 4, 5, 6][-20, 30, -56][-19, 31, -55]class Answer {
static boolean showExpectedResult = true;
static boolean showHints = true;
// Increment each number in the 'numbers' array by one
static int[] incrementArray(int[] numbers) {
for(int i = 0; i < numbers.length; i++){
numbers[i] = numbers[i] + 1;
}
return numbers;
}
// Main method to test the function
public static void main(String[] args) {
int[] testArray1 = {1, 2, 3, 4, 5};
int[] result1 = incrementArray(testArray1);
System.out.println(java.util.Arrays.toString(result1)); // Expected: [2, 3, 4, 5, 6]
int[] testArray2 = {-20, 30, -56};
int[] result2 = incrementArray(testArray2);
System.out.println(java.util.Arrays.toString(result2)); // Expected: [-19, 31, -55]
}
}
for loop iterates over each index in the numbers array.numbers[i] = numbers[i] + 1 increases each element by 1.numbers.main Method:java.util.Arrays.toString(result1) and java.util.Arrays.toString(result2) convert the array to a string format for easy printing.This approach makes it easy to verify that the incrementArray function works correctly.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.