Loops
Loops repeat code.
About this topic
A loop repeats a block of code, saving the programmer from writing the same lines many times. A for loop repeats a set number of times or once for each item in a collection, while a while loop continues as long as a condition remains true.
For example, a loop that prints the numbers 1 to 5 runs the print instruction five times, changing the counter each time. A loop that adds up all values in a list keeps a running total. The loop body must eventually make the condition false, otherwise you get an infinite loop that never ends, which is a classic bug. Loops can be nested, so a loop inside a loop can produce a grid or multiplication table.
Loops process thousands of student records, animate game frames and keep servers waiting for requests. A common mistake is the off-by-one error, such as counting to 9 instead of 10 because the end value is excluded in many languages. Another is forgetting to update the counter in a while loop. Trace the first few passes by hand to understand and debug a loop.
Key ideas
- for loops count
- while loops test a condition
- Avoid infinite loops
Quick check
Use cases: where Loops helps
- Homework: review the key idea behind Loops before you start a problem set.
- Exam revision: use the quick check to test whether you can recall Loops without notes.
- Visual learning: play with the interactive lab to see how Loops changes when you adjust its inputs.
- Teaching a friend: explain Loops in your own words, then compare your version with the key ideas.
Computing ideas run phones, search engines, games and the wider internet.
Frequently asked questions
What is Loops?
Loops repeat code.
What will I learn in Loops?
for loops count. while loops test a condition. Avoid infinite loops.
Is Loops part of Computer Science?
Yes. It is one of 80 Computer Science topics on LearnViz HighSchoolEdu, with 3 key ideas, a live animation and a quick check.
Does the Loops lab work on a phone or tablet?
Yes. The animation resizes to fit your screen and supports touch, so you can drag, tap and slide with your finger.
How should I study Loops?
Read the summary and key ideas first, play with the interactive lab to see the idea in motion, then answer the quick check. If you get a question wrong, go back to the key idea it tests.
Do I need an account, and is my progress saved?
No account is needed. Marking a topic as learned is saved in your own browser, so it stays on that device and is not sent to a server.