Home / Programs / Assignment: Using Java: Increment each number in an array by 1
Programming Example

Assignment: Using Java: Increment each number in an array by 1

👁 139 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

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 Code

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]
    }
}

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.

How to learn from this program

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.