💻 Computer Science · Topic 26 of 80

Loops

Loops repeat code.

Interactive labFollow the idea step by step

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

  1. for loops count
  2. while loops test a condition
  3. Avoid infinite loops

Quick check

Use cases: where Loops helps

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.

More in Computer Science