BeginnerTopic 6 of 104Software & Computing

Loops

for and while repeat code; careful termination conditions avoid infinite loops.

In depth

Loops repeat code: for iterates over a range or collection, while repeats until a condition fails. break exits, continue skips an iteration. Ensure the condition eventually becomes false; off-by-one errors are common. Complexity grows with nested loops.

Key points

  • Loop invariants
  • Iterators and comprehensions
  • Infinite loop hazards
Example

Summing 1 to 100 with a for loop gives 5050.

Why it matters

Loops repeat work over data or until a condition is met, which is how programs process lists, streams and time-based tasks.

Where this is used

  • Processing every line of a log file.
  • Polling a sensor until it reports ready.
  • Computing a running total over a series of measurements.

Frequently asked questions

What is Loops?

for and while repeat code; careful termination conditions avoid infinite loops.

Why is it important to understand loops?

Loops repeat work over data or until a condition is met, which is how programs process lists, streams and time-based tasks.

When should I use for versus while?

Use for when you know the number of iterations or are walking a collection, and use while when the stopping depends on a condition that may change.

How do I avoid an infinite loop?

Make sure the condition will eventually become false, update the loop variable correctly, and include a timeout or guard where input is external.

How is Loops used in practice?

Typical applications include processing every line of a log file, polling a sensor until it reports ready and computing a running total over a series of measurements.

What should I learn before Loops?

Study "Control flow" first (topic 5 of 104 in Software & Computing). It covers the groundwork this topic builds on.

What are the key points of Loops?

Loop invariants. Iterators and comprehensions. Infinite loop hazards.

Can you give an example of Loops?

Summing 1 to 100 with a for loop gives 5050.

What comes after Loops?

The next topic is "Functions", which builds directly on this one.

How difficult is Loops?

It is classed as Beginner in Software & Computing (topic 6 of 104). It is an entry-level topic. It relies only on basic school mathematics and the ideas introduced earlier in this discipline.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.

Related topics