AP Computer Science A Unit 6 Review

AP Computer Science A Unit 6 Review with Java Code….

1. Array Creation and Access

public class ArrayCreationExample {
    public static void main(String[] args) {
        // Creating an array of integers with size 5
        int[] numbers = new int[5];
        
        // Initializing the array
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;
        
        // Accessing elements using indices
        System.out.println("First element: " + numbers[0]); // Output: 10
        System.out.println("Last element: " + numbers[4]); // Output: 50
    }
}

2. Traversing Arrays

public class ArrayTraversingExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Traditional for loop to traverse the array
        System.out.println("Using traditional for loop:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
        
        // Enhanced for loop (for-each) to traverse the array
        System.out.println("\nUsing enhanced for loop:");
        for (int number : numbers) {
            System.out.println("Element: " + number);
        }
    }
}

3. Developing Algorithms Using Arrays

public class ArrayAlgorithmsExample {
    public static void main(String[] args) {
        int[] numbers = {15, 3, 8, 23, 7, 12};
        
        // Finding the maximum value in the array
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        System.out.println("Maximum value in the array: " + max);
        
        // Finding the minimum value in the array
        int min = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }
        System.out.println("Minimum value in the array: " + min);
        
        // Calculating the sum of the array elements
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("Sum of array elements: " + sum);
    }
}