Ever wondered how to quickly find the total sum of all numbers from 1 up to a certain value? Whether it’s for a math problem, a leaderboard calculation, or just good practice, you can easily do this in Apex with a simple loop.
In this post, we’ll create an Apex method that accepts a number and returns the sum of all integers from 1 up to that number. If you’re learning Apex and want to build your confidence with loops and logic, this one’s a great place to start!
🧠 What Are We Trying to Do?
Let’s say we call the method with the input 5.
We want to calculate:
The method should:
Accept a final number
Loop from 1 to that number
Add each number to a total
Return the total at the end
This is also a great introduction to for-loops and accumulation logic in Apex.
🔍 Code Explanation
We define a class called ApexUseCaseSixteen and create a static method sumOfAll that takes one input: the number we want to sum up to.
We initialize a variable totalSum to 0. This is where we’ll store our running total.
Here’s the loop:
We start from
1and go up to (and including)finalNumberOn each loop, we add
itototalSumusing the shorthand+=
This way, the method adds 1 + 2 + 3 + … until it reaches the number we passed in.
Finally, we return the sum back to the caller.
✅ Why This Is Useful
This small method packs a lot of learning:
It teaches for-loops
Shows how to build running totals
Gives real-world value in areas like:
Scores and points
Total prices
Task counters
Any place where cumulative sums matter
Want to level it up?
You could skip the loop and use the formula:
n(n + 1)/2for instant resultsAdd input validation (like if the number is less than 1)
Return the total as a string with a message
🧾 Final Code Snippet
🎥 Watch It in Action!
Prefer watching instead of reading? I’ve created a short demo where I run this method inside the Developer Console and explain each step visually.
Want to go further with this?
Learn it step by step in a course, or talk it through on a 1:1 call.
