Menu
Coddy logo textTech

Running Totals

Part of the Fundamentals section of Coddy's Solidity journey. Lesson 33 of 53.

An accumulator stores a result as a loop proceeds. Initialize it before the loop so each iteration builds on the previous total. The shorthand total += value means the same as total = total + value.

The statements in this excerpt run inside the provided main function.

uint256 total = 0;
for (uint256 i = 1; i <= 4; i++) {
    total += i;
}
console.log(total);

The accumulator passes through one, three, six and ten. Printing after the loop displays the final result only. Reinitializing total inside each iteration would throw away the earlier work.

Initialize an accumulator before the loop and update it inside the loop.

challenge icon

Challenge

Easy

Use a loop to add the integers from 1 through n, then print the sum. n is between 0 and 15.

The tests pass arguments to main in this order: uint256 n. 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 n) external view {
        // Write your solution here.
    }
}
quiz iconTest yourself

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