- Write
while,do…whileandforloops. - Control loops with
breakandcontinue. - 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:
- Initialisation – the starting value of the loop counter;
- Condition – tested before each repetition;
- 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/purefunctions 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.
breakexits a loop;continueskips to the next iteration.- Loops cost gas per iteration – avoid unbounded loops in state-changing functions.
The PDF E-Notes are the earlier printable version of this chapter. The notes on this page are the latest, revised version.
Question / Answer (15 questions)
for (initialisation; condition; update) { ... } – the initial value of the counter, the test condition and the increment/decrement step.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.
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.
- 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
- Solidity Team. (n.d.). Security Considerations. Solidity Documentation. https://docs.soliditylang.org/en/latest/security-considerations.html
- ethereum.org. (n.d.). Gas and fees. Ethereum Developer Documentation. https://ethereum.org/en/developers/docs/gas/
- Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language (2nd ed.). Prentice Hall.
- 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.