Unit 4: Iteration (The Power of Repetition)
Welcome to Unit 4! In the previous units, we learned how to make decisions using if statements. But what happens when we want to do something more than once? Imagine if you had to write 100 lines of code just to print the numbers 1 to 100. That would be exhausting! This is where iteration (commonly known as loops) comes in. Iteration allows us to repeat a block of code as many times as we need, making our programs efficient and powerful. This unit is the "engine" that helps us process large "collections" of data later on!
4.1 The while Loop
The while loop is the most basic form of iteration. It repeats a block of code as long as a boolean condition remains true. You can think of it like a "repeating if-statement."
The Real-World Analogy: Imagine you are eating a bowl of cereal. While the bowl is not empty, you take another bite. You check the condition (Is it empty?) before every single bite.
How it works:
1. The program checks the condition.
2. If it is true, the code inside the loop runs.
3. The program goes back to the top and checks the condition again.
4. This continues until the condition becomes false.
Common Mistake: The Infinite Loop
If the condition never becomes false, the loop will run forever! This usually happens because we forgot to update the variable we are checking. For example, if you are counting from 1 to 10 but forget to add 1 each time, you will be stuck at 1 forever.
Quick Review:
- A while loop checks the condition before running the code.
- If the condition is false the very first time it's checked, the code inside will never run.
4.2 The for Loop
While a while loop is great for when you don't know exactly how many times you'll repeat, a for loop is perfect when you know exactly how many times you want to run the code.
The Three Parts of a for Loop:
A standard for loop has three parts separated by semicolons:
1. Initialization: Where do we start? (e.g., \( i = 0 \))
2. Boolean Expression: When do we stop? (e.g., \( i < 10 \))
3. Increment/Decrement: How do we change the variable? (e.g., \( i++ \))
Memory Aid: Start, Stay, Step
- Start: Set your starting value.
- Stay: Stay in the loop as long as this is true.
- Step: Take a step toward the end (add or subtract).
Did you know?
You can always turn a for loop into a while loop, but for loops are often preferred because they keep all the "counting" logic in one neat line, making it harder to accidentally create an infinite loop!
Key Takeaway: Use a for loop when you have a definite starting point and ending point.
4.3 Developing Algorithms Using Strings
One of the most common uses for loops in AP Computer Science A is looking at Strings one character at a time. This is called traversing a String.
The Method to Remember: .substring()
To look at characters, we use \( String.substring(i, i+1) \). This pulls out exactly one character at index \( i \). Since loops use a counter that changes every time, we can visit index 0, then index 1, then index 2, and so on.
Important Note on String Length:
The last index of a String is always \( length() - 1 \). If you try to access the index equal to the length, your program will crash with an StringIndexOutOfBoundsException.
Don't worry if this seems tricky! Just remember: always stop your loop when \( i < string.length() \).
Common Algorithms:
- Counting: "How many times does the letter 'e' appear in this sentence?"
- Filtering: "Create a new string that only contains the vowels from the original string."
- Reversing: "Print the string backwards by starting the loop at the end and counting down to 0."
4.4 Nested Iteration
Nested iteration is just a fancy way of saying "a loop inside of another loop."
The Clock Analogy:
Think of a digital clock. The inner loop is like the "seconds." It has to go from 0 all the way to 59 before the "minutes" (the outer loop) can change by just one.
For every single "turn" of the outer loop, the inner loop runs its entire cycle.
Visualizing Nested Loops:
Nested loops are often used to print patterns, like a grid of stars:
- The outer loop controls the rows (vertical).
- The inner loop controls the columns (horizontal).
Quick Tip: If the outer loop runs 5 times and the inner loop runs 10 times, the code inside the inner loop will execute a total of \( 5 \times 10 = 50 \) times.
4.5 Informal Code Analysis
In this section, we look at how many times a loop actually runs. This helps us understand if our code is efficient.
Off-by-One Errors:
This is the most common mistake for students. Does the loop run 4 times or 5 times?
- \( for (int i = 0; i < 5; i++) \) runs 5 times (0, 1, 2, 3, 4).
- \( for (int i = 1; i <= 5; i++) \) runs 5 times (1, 2, 3, 4, 5).
- \( for (int i = 0; i <= 5; i++) \) runs 6 times (0, 1, 2, 3, 4, 5).
Statement Execution Counts:
To find the total number of times a nested loop runs, multiply the number of iterations of the outer loop by the number of iterations of the inner loop. If the inner loop depends on the outer loop (like a triangle shape), you may need to trace it step-by-step.
Key Takeaway: Always "trace" your code with a small number (like 3) to see if it behaves the way you expect before assuming it works for 1,000.
Unit Summary
1. while loops: Use when you don't know the exact number of repetitions.
2. for loops: Use when you have a specific range or count.
3. String Traversal: Use loops and .substring() to examine text character by character.
4. Nested Loops: An inner loop completes its full cycle for every single step of the outer loop.
5. Efficiency: Be careful with "off-by-one" errors by checking your loop boundaries (\( < \) vs \( <= \)).