AP Computer Science A Unit 4 Review

AP Computer Science A Unit 4 Review with Java Codes

1. while Loops

public class WhileLoopsExample {
    public static void main(String[] args) {
        int counter = 0;
        
        // while loop
        while (counter < 5) {
            System.out.println("Counter: " + counter);
            counter++; // Increment the counter
        }
    }
}

2. for Loops

public class ForLoopsExample {
    public static void main(String[] args) {
        // for loop
        for (int i = 0; i < 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

3. Developing Algorithms Using Strings

public class StringAlgorithmsExample {
    public static void main(String[] args) {
        String text = "Hello, World!";
        
        // Counting characters using a for loop
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == 'o') {
                count++;
            }
        }
        System.out.println("Count of 'o': " + count);
        
        // Replacing characters using a while loop
        String modifiedText = text;
        int index = 0;
        while (index < modifiedText.length()) {
            if (modifiedText.charAt(index) == 'o') {
                // Replace 'o' with 'a'
                modifiedText = modifiedText.substring(0, index) + 'a' + modifiedText.substring(index + 1);
            }
            index++;
        }
        System.out.println("Modified text: " + modifiedText);
    }
}

4. Nested Iteration

public class NestedIterationExample {
    public static void main(String[] args) {
        // Nested loops example
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}