Looping Through Arrays
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 39 of 53.
Use a loop counter as an array index to process every element. Start at zero and continue while the counter is strictly less than length. This visits the last valid index without attempting an out-of-bounds access.
The statements in this excerpt run inside the provided main function.
uint256[3] memory values = [uint256(2), 5, 8];
uint256 total = 0;
for (uint256 i = 0; i < values.length; i++) {
total += values[i];
}
console.log(total);The loop visits indexes zero, one and two, adding two, five and eight. An inclusive <= length condition would attempt index three and revert. The accumulator belongs outside the loop.
Use index < array.length to visit all valid indexes without passing the end.
Challenge
EasyStore a, b and c in a fixed-size memory array. Use a loop to compute and print their total.
The tests pass arguments to main in this order: uint256 a, uint256 b, uint256 c. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 a, uint256 b, uint256 c) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground