Post

Created by @nathanedwards
 at November 2nd 2023, 4:01:05 pm.

Question:

You are given an array nums of integers. Write a Java method traverseAndMultiply that performs the following operations:

  1. Traverse the array starting from index 0 to the end of the array.
  2. Multiply each element of the array by 2.
  3. Print the modified array.

The method should have the following signature:

public static void traverseAndMultiply(int[] nums)

Example:

Input: int[] nums = {1, 2, 3, 4, 5}

Output: [2, 4, 6, 8, 10]

Note:

  • Your method should not return anything, just print the modified array.

Answer:

public class ArrayTraversal {
    public static void traverseAndMultiply(int[] nums) {
        // Traverse the array starting from index 0 
        // Iterate using a standard for loop
        for (int i = 0; i < nums.length; i++) {
            // Multiply each element of the array by 2
            nums[i] *= 2;
        }

        // Print the modified array
        System.out.print("[");
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]);

            // Add comma and space for elements except the last one
            if (i < nums.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        traverseAndMultiply(nums);
    }
}

Explanation:

The traverseAndMultiply method takes an array of integers nums as input. It uses a for loop to traverse the array and multiply each element by 2. The modified array is then printed using another for loop.

In the for loop, the variable i is used as the index to access each element. The element is multiplied by 2 using the compound assignment operator *=, which is short for nums[i] = nums[i] * 2.

After multiplying each element, the modified array is printed. First, the opening square bracket [ is printed. Then, each element of the array is printed using a for loop. A comma and space are added after each element, except for the last one. Finally, the closing square bracket ] is printed, resulting in the modified array being displayed.