Programming LogicIntermediate· 10 min read

Loops

Loops allow executing blocks of code multiple times without duplicating instructions. Learn about for, while, do-while, and best practices to avoid errors.

RF

Renato Freitas

Updated on May 5, 2026

Why loops exist

Imagine you need to display 'Good morning!' 100 times. Without loops, you would write the same instruction 100 times — tedious, error-prone, and impossible to maintain. With a loop, you write the instruction once and tell the computer how many times to repeat it.

Loops are the main tool for processing collections of data: summing all values in a list, finding the largest number in a set, checking whether an element exists in an array. Without loops, you could only process a fixed and known number of elements.

The central idea is simple: while a condition is true, execute this block of instructions. When the condition becomes false, stop. The challenge lies in ensuring the condition eventually becomes false — otherwise, the program freezes in an infinite loop.

🧮 Try it yourself — CalcSim

Want more features? Download CalcSim IA app

The for loop: when you know the number of repetitions

The 'for' loop is ideal when you know in advance how many times the block should execute. Its structure has three parts: initialization (creates and sets the counter), condition (while true, continue), and increment (updates the counter each cycle).

Pseudocode: FOR i FROM 1 TO 10 DO (display i). This displays the numbers 1 to 10. The counter 'i' starts at 1, the block executes, i increments to 2, the block executes again, and so on until i reaches 11, when the condition 'i <= 10' becomes false and the loop stops.

A very common use is traversing a list by index: FOR i FROM 0 TO list_size - 1 DO (process list[i]). Note that lists generally start at index 0, so the last index is 'size - 1'.

The while loop: when the condition is dynamic

The 'while' loop is used when you do not know in advance how many iterations will be needed — the repetition continues while a condition is true. Example: reading user input until the user types 'quit'.

Pseudocode: WHILE (input != 'quit') DO (process input; read new input). The condition is checked before each execution of the block. If the condition is already false on the first check, the block never executes.

The while loop is natural for situations like: waiting for a network connection, processing a file line by line until the end, or retrying an attempt until it succeeds.

Do-while, infinite loops, break, and continue

The 'do-while' guarantees that the block executes at least once, because the condition is checked after the first execution. It is useful for input validation: execute the prompt, then check whether the response is valid.

An infinite loop occurs when the condition never becomes false: WHILE (true) DO (...) without an explicit exit. This freezes the program. To prevent it, always ensure some instruction inside the loop modifies the variables of the stopping condition.

The 'break' keyword forces an immediate exit from the loop, regardless of the condition. The 'continue' keyword skips to the next iteration without executing the rest of the current block. Both should be used sparingly — overuse makes the logic hard to follow.

  • for: number of repetitions known in advance
  • while: condition checked before each iteration
  • do-while: guarantees at least one execution
  • break: immediately exits the loop
  • continue: skips to the next iteration

Practical examples

Sum of a series: sum = 0; FOR i FROM 1 TO 100 DO sum = sum + i. Result: 5050. This is one of the most classic algorithms for introducing loops.

Search in a list: FOR i FROM 0 TO size - 1 DO IF (list[i] == searchValue) THEN display 'Found at position i' AND BREAK. The 'break' avoids continuing the search after finding the element.

Counting even numbers: counter = 0; FOR i FROM 1 TO 1000 DO IF (i MOD 2 == 0) THEN counter = counter + 1. The MOD operator returns the remainder of the division — if the remainder when divided by 2 is zero, the number is even.

Frequently asked questions

When should I use for versus while?

Use for when the number of iterations is known or can be calculated before the loop (traversing a list, counting to N). Use while when the stopping condition depends on something that changes during execution (user input, network data, calculation result).

What is a nested loop and what is the performance cost?

A loop inside another loop. For each iteration of the outer loop, the inner loop completes all of its iterations. If the outer loop has N iterations and the inner has M, the total is N×M executions. Nested loops have quadratic cost and should be avoided with large data sets.

How do I debug a loop that seems not to end?

Add an instruction to display the value of the control variable at each iteration. Check whether the stopping condition is correct (wrong operator, wrong variable), whether the increment actually happens, and whether some instruction is accidentally resetting the counter.

What are iterators and what are they for?

Iterators are objects that abstract the logic of traversing a collection. Instead of managing indices manually, you use 'for each element in collection do'. They are safer (no risk of index out of bounds) and more readable than loops with explicit counters.

Was this article helpful?

Rate with stars to help us improve the content.

Sign in to rate this article.

Still have questions?

The AI Professor explains step by step

Ask a question in natural language and get a personalised explanation about Programming Logic — or any other topic.

Prefer to solve it on your phone?

Download the free app →

Keep learning