0
0
Blockchain / Solidityprogramming~20 mins

For and while loops in Blockchain / Solidity - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Mastery in Blockchain
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a for loop in a smart contract
What is the output of this Solidity code snippet when the function sumUpToFive() is called?
Blockchain / Solidity
pragma solidity ^0.8.0;
contract LoopTest {
    function sumUpToFive() public pure returns (uint) {
        uint sum = 0;
        for (uint i = 1; i <= 5; i++) {
            sum += i;
        }
        return sum;
    }
}
A0
B10
C5
D15
Attempts:
2 left
💡 Hint
Add numbers from 1 to 5 using a loop.
Predict Output
intermediate
2:00remaining
While loop behavior in a blockchain contract
What will be the value of counter after calling countDown() in this Solidity contract?
Blockchain / Solidity
pragma solidity ^0.8.0;
contract LoopCountdown {
    function countDown() public pure returns (uint) {
        uint counter = 5;
        while (counter > 0) {
            counter--;
        }
        return counter;
    }
}
A1
B0
C5
DUndefined behavior
Attempts:
2 left
💡 Hint
The loop decreases counter until it is no longer greater than zero.
🔧 Debug
advanced
2:00remaining
Identify the error in this for loop
This Solidity function is intended to sum numbers from 1 to 3, but it causes a compilation error. What is the cause?
Blockchain / Solidity
pragma solidity ^0.8.0;
contract LoopError {
    function sumThree() public pure returns (uint) {
        uint sum = 0;
        for (uint i = 1; i < 4; i++)
            sum += i;
        return sum;
    }
}
AMissing semicolon after sum += i
BReturn statement inside the loop
CVariable i is not declared
DIncorrect loop condition syntax
Attempts:
2 left
💡 Hint
Check punctuation after statements inside the loop.
Predict Output
advanced
2:00remaining
Output of nested loops in a smart contract
What is the output of the nestedSum() function below?
Blockchain / Solidity
pragma solidity ^0.8.0;
contract NestedLoops {
    function nestedSum() public pure returns (uint) {
        uint total = 0;
        for (uint i = 1; i <= 2; i++) {
            for (uint j = 1; j <= 3; j++) {
                total += i * j;
            }
        }
        return total;
    }
}
A9
B12
C18
D6
Attempts:
2 left
💡 Hint
Multiply i and j for each pair and add all results.
🧠 Conceptual
expert
2:00remaining
Gas cost implications of loops in blockchain
Which statement best describes the gas cost behavior of loops in Ethereum smart contracts?
AGas cost increases linearly with the number of loop iterations
BLoops do not consume gas in smart contracts
CGas cost decreases as loops run longer due to optimization
DGas cost is fixed regardless of loop iterations
Attempts:
2 left
💡 Hint
Think about how Ethereum charges for computation steps.