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

You're given an array of integers.
Your task: Increment each number in the 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 numbers array always contains at least one number.
  • Each integer can be either positive or negative.

Example 1:

Input: [1, 2, 3, 4, 5]
Result: [2, 3, 4, 5, 6]

Example 2:

Input: [-20, 30, -56]
Result: [-19, 31, -55]

Want a hint?

Learn about Java arrays.

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:

  1. Loop through the Array: The for loop iterates over each index in the numbers array.
  2. Incrementing: Inside the loop, numbers[i] = numbers[i] + 1 increases each element by 1.
  3. Return the Modified Array: After the loop completes, the method returns the modified array numbers.

Explanation of main Method:

  1. Test Cases: Two test cases are created to verify the function with different sets of values.
  2. Print Results: 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.


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.