Learning Objectives – after this chapter you will be able to:
  • Write while, do…while and for loops.
  • Control loops with break and continue.
  • Explain why unbounded loops are dangerous on a blockchain.
Loop

A loop makes a program perform a set of statements again and again until a condition becomes false, which ends the loop. Solidity has three looping statements:

  • while loop
  • do…while loop
  • for loop
while loop

The condition is checked first. If it is true, the body runs and the condition is checked again; if it is false at the start, the body never runs (zero or more iterations).

while (condition) {
    statement1;
    statement2;
}
do…while loop

The body runs first and the condition is checked at the end, so the body always executes at least once. It repeats as long as the condition is true.

do {
    statement1;
    statement2;
} while (condition);
for loop

A compact loop used when the number of repetitions is known. It needs three parts:

  1. Initialisation – the starting value of the loop counter;
  2. Condition – tested before each repetition;
  3. Update – increases or decreases the counter after each repetition.
for (initialisation; condition; update) {
    statement1;
    statement2;
}
break and continue
  • break – exits the loop immediately.
  • continue – skips the rest of the current iteration and moves to the next one.
Loops and Gas
  • Every iteration costs gas. A block has a gas limit, so a loop that runs too many times makes the transaction fail with “out of gas”.
  • Avoid unbounded loops over arrays that anyone can grow (for example looping over all users). An attacker could add many entries and permanently block the function – a denial-of-service risk.
  • Prefer mappings for look-ups, limit array sizes, or process data in batches.
  • Loops in view/pure functions called off-chain cost no fee, but they are still limited by the node’s gas cap.
Example : All Three Loops
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract LoopsDemo {
    uint[] public numbers = [5, 12, 7, 20, 3];

    // for loop: sum of 1..n
    function sumTo(uint n) public pure returns (uint total) {
        for (uint i = 1; i <= n; i++) {
            total += i;
        }
    }

    // while loop: count digits of a number
    function countDigits(uint n) public pure returns (uint digits) {
        if (n == 0) return 1;
        while (n > 0) {
            n /= 10;
            digits++;
        }
    }

    // do...while: runs at least once
    function doWhileDemo(uint start) public pure returns (uint runs) {
        do {
            runs++;
            start++;
        } while (start < 3);
    }

    // break and continue
    function firstAbove(uint limit) public view returns (uint value, bool found) {
        for (uint i = 0; i < numbers.length; i++) {
            if (numbers[i] <= limit) continue;   // skip small values
            return (numbers[i], true);           // stop at the first match
        }
        return (0, false);
    }
}
Key Takeaways
  • while: 0 or more runs; do…while: at least 1 run; for: known number of runs.
  • break exits a loop; continue skips to the next iteration.
  • Loops cost gas per iteration – avoid unbounded loops in state-changing functions.
Download | Print      E-Notes

The PDF E-Notes are the earlier printable version of this chapter. The notes on this page are the latest, revised version.

Video : Loops in Solidity
Resource File
Question / Answer (15 questions)

Answer : A loop repeatedly executes a block of statements while a condition remains true; when the condition becomes false, the loop ends.

Answer : while, do…while and for.

Answer : (a) A while loop can make 0 iterations because the condition is checked first. (b) A do…while loop makes at least 1 iteration because the condition is checked after the body.

Answer : for (initialisation; condition; update) { ... } – the initial value of the counter, the test condition and the increment/decrement step.

Answer : When the number of repetitions is known in advance, such as iterating over an array with an index; a while loop suits cases where repetitions depend on a changing condition.

Answer : It immediately exits the nearest enclosing loop and continues with the statement after the loop.

Answer : It skips the rest of the current iteration and jumps to the next iteration (re-checking the condition, and running the update step in a for loop).

Answer : Each iteration costs gas and every block has a gas limit. If a loop grows with data that users can add, it may eventually need more gas than allowed, making the function permanently unusable (a denial-of-service risk).

Answer : Use mappings for direct look-ups, cap the size of arrays, process data in fixed-size batches, or let users withdraw individually instead of looping over everyone.

Answer : When a view function is called off-chain (eth_call) the caller pays no fee, but execution is still limited by the node’s gas cap. If the view function is called inside a transaction, its gas is charged.

Answer : 1 + 2 + 3 + 4 = 10.

Answer : 4. The while loop divides n by 10 until it becomes 0, counting each division (2026 → 202 → 20 → 2 → 0).

Answer : Once. The body runs first, then the condition 6 < 3 is false, so the loop stops.

Answer : An infinite loop never meets its stop condition. In Solidity it runs until the transaction runs out of gas, at which point the transaction reverts and the gas used is lost.

Answer : To skip values that are not greater than the limit and move straight to the next element, keeping the loop body simple.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which loop always executes its body at least once?

Show Answer

Correct Answer : C. do…while
do…while checks the condition after the body.

Q2. Which statement exits a loop immediately?

Show Answer

Correct Answer : B. break
break leaves the loop.

Q3. The main risk of looping over a user-growable array in a transaction is:

Show Answer

Correct Answer : D. Exceeding the gas limit
Large loops can exceed the block gas limit.

Q4. What does sumTo(5) return?

Show Answer

Correct Answer : C. 15
1+2+3+4+5 = 15.

Q5. In a for loop, which part runs after each iteration?

Show Answer

Correct Answer : B. Update (increment/decrement)
The update step runs after the body, before the condition is re-checked.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Solidity Team. (n.d.). Expressions and Control Structures (if/else, loops, checked arithmetic, error handling, try/catch). Solidity Documentation. https://docs.soliditylang.org/en/latest/control-structures.html
  2. Solidity Team. (n.d.). Security Considerations. Solidity Documentation. https://docs.soliditylang.org/en/latest/security-considerations.html
  3. ethereum.org. (n.d.). Gas and fees. Ethereum Developer Documentation. https://ethereum.org/en/developers/docs/gas/
  4. Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language (2nd ed.). Prentice Hall.
  5. Modi, R. (2018). Solidity Programming Essentials: A beginner’s guide to build smart contracts for Ethereum and blockchain. Packt Publishing. ISBN 978-1-78883-138-3.