Assignment: Using Java: Increment each number in an array by 1
Java Programming Language Array in java (Article) Array in java (Program)
120
Increment each number in an array by 1
Parameters
numbers: An array of integers
Result
result: A new array of integers, where 1 has been added to each number in the original array
Constraints
- The
numbersarray always contains at least one number. - Each integer can be either positive or negative.
Example 1:
[1, 2, 3, 4, 5][2, 3, 4, 5, 6]Example 2:
[-20, 30, -56][-19, 31, -55]Want a hint?
Program:
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] } }
Output:
Explanation:
Explanation of the Code:
- Loop through the Array: The
forloop iterates over each index in thenumbersarray. - Incrementing: Inside the loop,
numbers[i] = numbers[i] + 1increases each element by 1. - Return the Modified Array: After the loop completes, the method returns the modified array
numbers.
Explanation of main Method:
- Test Cases: Two test cases are created to verify the function with different sets of values.
- Print Results:
java.util.Arrays.toString(result1)andjava.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.
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.