0
0
Blockchain / Solidityprogramming~15 mins

For and while loops in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - For and while loops
What is it?
For and while loops are ways to repeat a set of instructions multiple times in a program. A for loop repeats actions a specific number of times, while a while loop repeats as long as a condition is true. These loops help automate tasks that need to happen many times without writing the same code again and again.
Why it matters
Without loops, programmers would have to write repetitive code for every repeated action, making programs long, hard to read, and error-prone. Loops make blockchain smart contracts and scripts efficient by handling repeated checks or actions automatically, saving time and reducing mistakes.
Where it fits
Learners should first understand basic programming concepts like variables and conditions before learning loops. After mastering loops, they can explore more complex topics like recursion, event-driven programming, and optimizing smart contract gas usage.
Mental Model
Core Idea
Loops let a program repeat tasks automatically until a condition says stop or a set number of times is reached.
Think of it like...
Imagine a factory worker who needs to place stickers on 100 boxes. Instead of telling them to place a sticker on each box one by one, you tell them to repeat the sticker action 100 times. The worker keeps doing the same task until all boxes are done.
┌───────────────┐       ┌───────────────┐
│   Start Loop  │──────▶│ Check Condition│
└───────────────┘       └───────────────┘
          │                      │
          │Yes                   │No
          ▼                      ▼
┌───────────────┐        ┌───────────────┐
│ Execute Body  │        │   End Loop    │
└───────────────┘        └───────────────┘
          │
          └───────────────┐
                          ▼
                   (Repeat Loop)
Build-Up - 7 Steps
1
FoundationUnderstanding Repetition in Code
🤔
Concept: Introduce the idea that some tasks need to happen multiple times and writing code repeatedly is inefficient.
Imagine you want to print numbers 1 to 5. Writing print statements five times is repetitive: print(1) print(2) print(3) print(4) print(5) This is tedious and error-prone.
Result
You see that repeating code manually is slow and can cause mistakes.
Understanding why repetition is a problem helps appreciate why loops exist.
2
FoundationBasic For Loop Structure
🤔
Concept: Learn how a for loop repeats a block of code a fixed number of times.
A for loop sets a counter and repeats code while increasing it: for (uint i = 1; i <= 5; i++) { // code to repeat print(i); } This prints numbers 1 to 5 automatically.
Result
The numbers 1 to 5 print without writing print five times.
Knowing how to control repetition with a counter is the foundation of loops.
3
IntermediateWhile Loop Basics
🤔
Concept: Learn how a while loop repeats code as long as a condition is true, without a fixed count.
A while loop checks a condition before each repetition: uint i = 1; while (i <= 5) { print(i); i++; } This also prints numbers 1 to 5 but stops when i > 5.
Result
The loop runs until the condition becomes false, printing numbers 1 to 5.
Understanding condition-based repetition allows flexible looping beyond fixed counts.
4
IntermediateLoop Control with Break and Continue
🤔Before reading on: Do you think 'break' stops the current iteration or the entire loop? Commit to your answer.
Concept: Learn how to control loops by skipping steps or stopping early using break and continue.
Inside loops, 'break' stops the whole loop immediately. 'continue' skips the rest of the current loop step and moves to the next. Example: for (uint i = 1; i <= 5; i++) { if (i == 3) break; // stops loop at 3 print(i); } This prints 1 and 2 only.
Result
Loop stops early when break runs; continue skips specific steps.
Knowing how to control loop flow prevents infinite loops and allows selective repetition.
5
IntermediateLoops in Blockchain Smart Contracts
🤔Before reading on: Do you think loops in smart contracts cost more or less gas when they run more times? Commit to your answer.
Concept: Understand how loops affect blockchain contract costs and why careful use matters.
Each loop iteration uses gas, the blockchain's fee for computation. More iterations mean higher gas costs. Smart contracts must avoid loops that run too long or depend on user input to prevent expensive or stuck transactions.
Result
Loops can make contracts costly or fail if not designed carefully.
Knowing gas costs helps write efficient, safe blockchain code.
6
AdvancedAvoiding Infinite Loops in Blockchain
🤔Before reading on: Can a smart contract with an infinite loop ever finish executing? Commit to your answer.
Concept: Learn why infinite loops are dangerous in blockchain and how to prevent them.
An infinite loop never stops, causing the contract to run forever. Blockchain nodes stop execution when gas runs out, reverting changes. To avoid this, always ensure loop conditions will become false and limit iterations. Example safe pattern: uint max = 100; for (uint i = 0; i < max; i++) { // safe loop body } This prevents infinite loops by fixed max.
Result
Contracts avoid getting stuck and wasting gas.
Understanding loop termination is critical for reliable blockchain programs.
7
ExpertGas Optimization with Loop Unrolling
🤔Before reading on: Do you think manually writing repeated code can sometimes save gas compared to loops? Commit to your answer.
Concept: Explore how unrolling loops (writing repeated code explicitly) can reduce gas costs in some blockchain cases.
Loop unrolling means replacing a loop with repeated code lines: Instead of: for (uint i = 0; i < 3; i++) { doSomething(i); } Write: doSomething(0); doSomething(1); doSomething(2); This removes loop overhead but increases code size. Use when loop count is small and fixed.
Result
Gas costs can be lower because no loop control instructions run.
Knowing when to unroll loops balances gas cost and code size for optimal contracts.
Under the Hood
Loops work by setting a starting point and repeatedly executing code while checking a condition each time. For loops have an initialization, condition check, and update step. While loops only check a condition before each repetition. In blockchain, each loop iteration consumes gas, so the runtime tracks gas usage and stops execution if gas runs out, reverting all changes.
Why designed this way?
Loops were created to avoid repetitive code and make programs concise and flexible. The for loop's structure with initialization, condition, and update was designed for counting tasks. While loops offer more general repetition based on conditions. In blockchain, gas limits enforce loop termination to protect the network from infinite or costly computations.
┌───────────────┐
│ Initialization│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Condition?    │
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Loop Body     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Update Step   │
└──────┬────────┘
       │
       └─────┐
             ▼
       (Repeat Condition)
Myth Busters - 4 Common Misconceptions
Quick: Does a while loop always run at least once? Commit to yes or no.
Common Belief:A while loop always runs its code at least once.
Tap to reveal reality
Reality:A while loop checks the condition before running; if false initially, it never runs.
Why it matters:Assuming it runs once can cause logic errors and unexpected behavior.
Quick: Do you think for loops are always better than while loops? Commit to yes or no.
Common Belief:For loops are always better and should replace while loops.
Tap to reveal reality
Reality:For loops are best for counted repetition; while loops are better for condition-based repetition without a fixed count.
Why it matters:Choosing the wrong loop type can make code harder to read or cause bugs.
Quick: Can loops in smart contracts run forever without consequences? Commit to yes or no.
Common Belief:Loops can run forever in smart contracts without problems.
Tap to reveal reality
Reality:Infinite loops waste gas and cause contract execution to fail and revert.
Why it matters:Ignoring this can lead to failed transactions and lost fees.
Quick: Does using 'break' inside a loop only skip one iteration? Commit to yes or no.
Common Belief:'Break' skips only the current iteration and continues the loop.
Tap to reveal reality
Reality:'Break' stops the entire loop immediately.
Why it matters:Misusing break can cause loops to end too early, breaking program logic.
Expert Zone
1
Loops in blockchain must consider gas limits; even a correct loop can fail if it uses too much gas.
2
Using fixed-size loops or limiting iterations is a common pattern to avoid denial-of-service attacks.
3
Loop unrolling trades off code size for gas efficiency, a subtle optimization not obvious to beginners.
When NOT to use
Avoid loops when the number of iterations depends on untrusted user input or can be very large. Instead, use event-driven or off-chain computations to handle heavy repetition safely.
Production Patterns
In production smart contracts, loops are often used for small fixed-size arrays or batch processing with strict limits. Developers also use pagination patterns to process large data sets in multiple transactions.
Connections
Recursion
Recursion is an alternative to loops for repeating tasks by calling functions within themselves.
Understanding loops helps grasp recursion since both repeat actions, but recursion uses function calls instead of explicit loops.
Finite State Machines
Loops often implement repeated state checks or transitions in state machines.
Knowing loops clarifies how programs cycle through states repeatedly until conditions change.
Manufacturing Assembly Lines
Loops mirror assembly lines where the same step repeats for each product unit.
Seeing loops as assembly lines helps understand automation and efficiency in programming.
Common Pitfalls
#1Creating an infinite loop that never stops.
Wrong approach:uint i = 0; while (i < 5) { // forgot to increase i print(i); }
Correct approach:uint i = 0; while (i < 5) { print(i); i++; }
Root cause:Forgetting to update the loop variable causes the condition to never become false.
#2Using loops with unbounded user input causing high gas costs.
Wrong approach:function process(uint count) public { for (uint i = 0; i < count; i++) { // expensive operation } }
Correct approach:function process(uint count) public { require(count <= 100, "Too many iterations"); for (uint i = 0; i < count; i++) { // safe operation } }
Root cause:Not limiting loop iterations allows attackers to cause expensive or failing transactions.
#3Misusing break thinking it skips one iteration only.
Wrong approach:for (uint i = 0; i < 5; i++) { if (i == 2) break; print(i); // expects to skip only i=2 }
Correct approach:for (uint i = 0; i < 5; i++) { if (i == 2) continue; print(i); }
Root cause:Confusing break and continue leads to unexpected loop termination.
Key Takeaways
Loops automate repeating tasks, saving time and reducing errors in code.
For loops repeat a set number of times; while loops repeat based on conditions.
In blockchain, loops consume gas, so they must be used carefully to avoid costly or failing transactions.
Proper loop control with break and continue prevents infinite loops and controls flow precisely.
Advanced techniques like loop unrolling optimize gas but increase code size, showing tradeoffs in smart contract design.