Final challenge: add up, count and search
After this: Predict, trace, complete and count loops in five short programs.
This challenge has five steps, and each step is scored on its own. You will predict what a loop prints, trace its boxes after a pass, complete the condition of a while loop, count how many times the inner line of two nested loops runs, and say what a loop with a break prints. Every step shows the code in Python and in Java; the answers are the same in both. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 5Predict it
Predict it
The print line is inside the loop. What does this program print?
total = 0for n in [2, 4, 6]: total = total + n print(total)int total = 0;for (int n : new int[]{2, 4, 6}) { total = total + n; System.out.println(total);}Trace the boxes
After the second pass of this loop, what do count and i hold?
count = 0for i in range(1, 4): count = count + i * 2print(count)int count = 0;for (int i = 1; i < 4; i++) { count = count + i * 2;}System.out.println(count);Fill the condition
Complete the while line so that the program prints 5, 4, 3, 2, 1 and then stops. Write the whole line.
n = 5____________________ # ← keep going while n is at least 1 print(n) n = n - 1int n = 5;____________________ // ← keep going while n is at least 1 System.out.println(n); n = n - 1;}How many times
How many times does line 4, count = count + 1, run? That is also the number this program prints.
count = 0for a in range(1, 3): for b in range(1, 6): count = count + 1print(count)int count = 0;for (int a = 1; a < 3; a++) { for (int b = 1; b < 6; b++) { count = count + 1; }}System.out.println(count);Leaving early
What does this program print?
for n in [5, 8, 3]: if n > 6: break print(n)for (int n : new int[]{5, 8, 3}) { if (n > 6) { break; } System.out.println(n);}- Predict what a loop prints, trace its boxes after a pass, complete a while condition, count the passes of two loops, and say where a break stops.