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:
1 + 2 + 3 + 4 + 5 = 15
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
public with sharing class ApexUseCaseSixteen {
public static Integer sumOfAll(Integer finalNumber){
We define a class called ApexUseCaseSixteen
and create a static method sumOfAll
that takes one input: the number we want to sum up to.
Integer totalSum = 0;
We initialize a variable totalSum
to 0. This is where we’ll store our running total.
for(Integer i = 1; i <= finalNumber; i++){
totalSum += i;
}
Here’s the loop:
We start from
1
and go up to (and including)finalNumber
On each loop, we add
i
tototalSum
using the shorthand+=
This way, the method adds 1 + 2 + 3 + … until it reaches the number we passed in.
return totalSum;
}
}
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)/2
for instant resultsAdd input validation (like if the number is less than 1)
Return the total as a string with a message
🧾 Final Code Snippet
public with sharing class ApexUseCaseSixteen {
public static Integer sumOfAll(Integer finalNumber){
Integer totalSum = 0;
for(Integer i = 1; i <= finalNumber; i++){
totalSum += i;
}
return totalSum;
}
}
🎥 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.