Post

Created by @nathanedwards
 at November 1st 2023, 7:03:40 pm.

AP Computer Science Exam Question

Consider the following Java code:

public class ArrayTraversal {

    public static int[] modifyArray(int[] arr) {
        int[] modifiedArr = new int[arr.length];

        // Step 1: Traversing the array arr backwards
        for (int i = arr.length - 1; i >= 0; i--) {
            // Step 2: Doubling the value of the current element
            modifiedArr[i] = arr[i] * 2;
        }

        return modifiedArr;
    }

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

        // Step 3: Calling the modifyArray method
        int[] modifiedArray = modifyArray(myArray);

        // Step 4: Printing the modified array
        for (int element : modifiedArray) {
            System.out.print(element + " ");
        }
    }
}

What will be the output when the above code is executed?

A) 1 2 3 4 5 B) 2 4 6 8 10 C) 10 8 6 4 2 D) 5 4 3 2 1

Explain your answer with the detailed step-by-step explanation of the code.

Answer

The correct output will be B) 2 4 6 8 10.

Explanation:

  1. We define a class ArrayTraversal with a public static method modifyArray that takes an integer array arr as input and returns an integer array.

  2. In the modifyArray method, we first declare a new integer array modifiedArr with the same length as arr.

  3. Next, we traverse the array arr backwards starting from the last index (arr.length - 1) to the first index (0), inclusive, using a for loop.

  4. In each iteration of the loop, we double the value of the current element arr[i] and assign it to the corresponding element in modifiedArr using the same index i.

  5. Finally, we return the modifiedArr array.

  6. In the main method, we create an integer array myArray with the values {1, 2, 3, 4, 5}.

  7. We then call the modifyArray method, passing myArray as the argument, and assign the returned array to modifiedArray.

  8. We use a for-each loop to traverse the modifiedArray and print each element followed by a space. The output of this loop will be "2 4 6 8 10".

Therefore, the correct answer is B) 2 4 6 8 10.