✦
✦
Computer Science · Coding Basics
Loops and Repeated Actions
A loop tells the computer to repeat an action without writing a separate instruction for every repetition.
🤖Walking 100 steps
😫Repeated instructions
# write 100 instructions
Step Forward
Step Forward
Step Forward
… 96 more lines …
Step Forward
Step Forward
Step Forward
Step Forward
… 96 more lines …
Step Forward
100 separate instructions
➜
😎Using a loop
# write the action once
repeat 100 times:
Step Forward
repeat 100 times:
Step Forward
One action repeated 100 times
🔁Counted and conditional loops
🔢FOR LOOP
This example runs a specific number of times. A counter advances after each pass. The loop ends after its last count.
“Run 4 laps” means run four times.
❓WHILE LOOP
Runs while a condition stays true. It checks the condition before each pass and ends when that test is false.
🍽️ "Wash WHILE dishes are left"
⚙️Tracing one loop
Trace the condition and action.
1Check. Should the body run again?
2Run the action inside the loop (this is one iteration).
3Go back and check again. A false continuation test ends this loop.
An infinite loop
If you write a loop whose condition stays true, it can run forever and can keep other work from running. When a loop is meant to finish, give it a reachable stopping condition or a break).
🔑Key Terms
🔁Loop Code that repeats the same instructions over and over.
🔂Iteration A single pass through the instructions inside a loop.
🔢For Loop A loop that can repeat for each value in a sequence. A counted for loop can use a fixed number of iterations.
❓While Loop A loop that runs WHILE a condition stays true.
⚡Efficiency Using resources such as time or memory effectively. A shorter program is easier to read in this example, but it still takes 100 steps.
♾️Infinite Loop A loop that keeps running without an internal stopping point. It can be an error or an intentional part of a program.
⭐
Trace the 100-step example: one Step Forward instruction runs once on each iteration.
✏️ Computer Science Anchor Chart · Loops & Repeated Action