Big Idea 3: Algorithms and Programming · Topic 3.8 · Coding Practice
Iteration — Code It Yourself
Write real code and check it against the expected output. Pick Python or JavaScript; the AP pseudocode reference is there when you need it.
You warmed these up on paper in the Trace the Savings Loop and How Many Passes? exercises — Maya's savings jar. Now type and run them for real. The problems get harder as you go, ending with one you build from scratch. Predict the output first, then check yourself, hardest last.
Problem 1 of 4
Maya's jar starts at 0. Using a loop that repeats a fixed number of times, add 5 to savings four times, then print the final total. It should print exactly: 20
A count-controlled loop runs a set number of times. In Python, for i in range(4): runs its indented body exactly 4 times; add 5 to savings inside it, then print savings after the loop.
Problem 2 of 4
Maya's jar starts at 0 and she needs at least 20. Keep adding 5 each week untilsavings ≥ 20, counting the weeks. Print how many weeks it takes. It should print exactly: 4
REPEAT UNTIL(savings >= 20) becomes while savings < 20 — loop WHILE the condition is still false. Add 1 to weeks on every pass so weeks ends up equal to the number of passes.
Problem 3 of 4
This time Maya's jar already holds 25, and the loop is REPEAT UNTIL(savings ≥ 20) { savings ← savings + 5 }. Predict how many times the body runs, then write it and print the final savings. It should print exactly: 25
The condition is tested before the body runs. Since 25 >= 20 is already true (while 25 < 20 is false), the loop body never executes — the body runs ZERO times and savings prints unchanged as 25.
Problem 4 of 4
Build from scratch: Maya starts at 0 and deposits 3 each time. Count how many deposits it takes to reach at least 20, and print that count. It should print exactly: 7
Deposits of 3 give 3, 6, 9, 12, 15, 18, 21. After 6 deposits savings is 18, still under 20, so one more deposit is needed — 7 deposits reach 21. Loop while savings < 20 and count each pass.
Your code runs on a secure external service. Answers are checked automatically — nothing is stored.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed.
Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Typically responds within 24 hours
✓
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.