Solidity Loops
A loop is a block of code that runs again and again while a condition holds. Loops let a function work through a list or count up to a target in a few lines.
A for loop sums a stored array
The counter i visits each index of the scores array in turn. Each round adds that score to the running sum.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract SumScores {
uint256[] public scores;
constructor() {
scores.push(10);
scores.push(20);
scores.push(30);
}
function total() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum;
}
}
A while loop counts up to a target
The while loop raises count by one in each round. It stops as soon as count reaches the target.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract CountUp {
function countTo(uint256 target) public pure returns (uint256) {
uint256 count = 0;
while (count < target) {
count++;
}
return count;
}
}
A for loop can sum a fixed range
Here the counter itself is the value being added. Summing from 1 up to n builds the total one number at a time.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract SumFirst {
function sumFirst(uint256 n) public pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ScoreTotals {
uint256[] public scores;
constructor() {
scores.push(5);
scores.push(10);
scores.push(15);
scores.push(20);
}
function total() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum;
}
function countItems() public view returns (uint256) {
uint256 count = 0;
while (count < scores.length) {
count++;
}
return count;
}
}
Key points
- For loop: a loop with a start value, a condition, and a step, all written in one line.
- Counter: the variable a for loop raises by its step after each round.
- While loop: a loop that repeats its block while its condition stays true.
- Condition check: a while loop checks its condition before each round, so it may run zero times.
- Accumulator: a variable that gathers a running total, round by round, inside a loop.
- Array walk: i < scores.length keeps a loop inside the bounds of an array.
In this example, the ScoreTotals contract stores four scores in an array. The total function uses a for loop to visit each score and add it to a running sum, which ends at 50. The countItems function uses a while loop to count up until it reaches the array length, which ends at 4.
Note
keep loop counts small and fixed, since every extra round costs more work when the function runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
How many rounds does the while loop in countTo(5) run?