Given problem statment
During the final skill exam teacher was given a problem and asked everyone to write the algorithm to it, and also advised that try to implement a different approach from others
Question: Write an algorithm to calculate sum of first ‘n’ natural numbers
Methods to solve the problem
The simple solution is to intialize result as 0 and implement a for loop to increment the result.
A more elegant solution is to use the formula (n * (n + 1))/2
Java program to find the sum of first n natural numbers using for loop
class sum {
public static void main(String[] args) {
int sum = sumOfNNaturalNums(6);
System.out.println("sum is = " + sum);
}
public static int sumOfNNaturalNums(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
result += i;
}
return result;
}
}
Java program to find the sum of first n natural numbers using formula
class sum {
public static void main(String[] args) {
int sum = sumOfNNaturalNumsUsingFormula(6);
System.out.println("sum is = " + sum);
}
public static int sumOfNNaturalNumsUsingFormula(int n) {
return n * (n + 1) / 2;
}
}