Write a program in salesforce to calculate the sum of natural number.
- Abhilash Banpurkar
- Jan 17, 2023
- 1 min read
Here is an example of a Salesforce Apex class that calculates the sum of natural numbers up to a given number:
public class NaturalNumberSum {
public static Integer CalculateSum(integer n){
integer sum=0;
for(Integer i=0;i<=n;i++){
sum+=i;
}
return sum;
}
}

You can call this class from your Apex code or from a Visualforce page to calculate the sum of natural numbers up to a given number. For example, if you want to calculate the sum of natural numbers up to 5, you can call the following:
Integer result = NaturalNumberSum.calculateSum(5);
System.debug(result);
T

This will give you the sum of natural number upto 5 which is 15.

Comentários