Post

Created by @nathanedwards
 at October 31st 2023, 3:04:17 pm.

AP Computer Science Exam Question

You are given an array numbers of integers representing the heights of students in a classroom. Your task is to write a method manipulateArray to perform the following operations:

  1. Traverse the array and print out each integer value.

  2. Determine the average height of the students and return it.

  3. Replace any negative height values with 0 and print the updated array.

  4. Find the maximum height in the array and return it.

Your method should have the following signature:

public static int manipulateArray(int[] numbers)

Note: You may assume that the array numbers will always have at least one element.

For example, given the array [56, -12, 63, 8, -4, 20], the output would be:

Traversal:
56
-12
63
8
-4
20

Average height: 28

Array after replacing negative values:
56
0
63
8
0
20

Maximum height: 63

Write the implementation for the manipulateArray method and include any necessary explanations or assumptions in your answer.

Answer

You can use the following implementation for the manipulateArray method:

public static int manipulateArray(int[] numbers) {
    // Step 1: Traverse the array and print out each integer value
    System.out.println("Traversal:");
    for (int number : numbers) {
        System.out.println(number);
    }
    
    // Step 2: Calculate the average height of the students
    int sum = 0;
    for (int number : numbers) {
        sum += number;
    }
    int averageHeight = sum / numbers.length;
    System.out.println("\nAverage height: " + averageHeight);
    
    // Step 3: Replace any negative height values with 0 and print the updated array
    System.out.println("\nArray after replacing negative values:");
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] < 0) {
            numbers[i] = 0;
        }
        System.out.println(numbers[i]);
    }
    
    // Step 4: Find the maximum height in the array
    int max = Integer.MIN_VALUE;
    for (int number : numbers) {
        max = Math.max(max, number);
    }
    System.out.println("\nMaximum height: " + max);
    
    return averageHeight;
}

The implementation first traverses the array numbers and prints out each integer value. Then, it calculates the average height by summing up all the heights and dividing by the number of elements. Next, it replaces any negative values with 0 by iterating over each element of the array and checking if it is negative. After that, it prints the updated array. Finally, it finds the maximum height by iterating over the array and using Math.max() function.

The time complexity of this method is O(n), where n is the length of the input array.