You can find the sum of natural numbers in Java using a loop or a formula.
Using a Loop
- Initialize variables: Declare a variable to store the sum and set it to 0. Declare another variable to represent the number of natural numbers you want to sum.
- Iterate through the numbers: Use a loop (for loop or while loop) to iterate from 1 to the specified number.
- Add each number to the sum: Inside the loop, add the current number to the sum variable.
- Print the sum: After the loop completes, print the value of the sum variable.
Here's an example using a for loop:
public class SumOfNaturalNumbers {
public static void main(String[] args) {
int num = 10; // Change this to the desired number of natural numbers
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
}
System.out.println("The sum of natural numbers up to " + num + " is: " + sum);
}
}
Using a Formula
You can also use the formula for the sum of an arithmetic series to calculate the sum of natural numbers:
Sum = (n (n + 1)) / 2*
Where n is the number of natural numbers.
Here's an example using the formula:
public class SumOfNaturalNumbers {
public static void main(String[] args) {
int num = 10; // Change this to the desired number of natural numbers
int sum = (num * (num + 1)) / 2;
System.out.println("The sum of natural numbers up to " + num + " is: " + sum);
}
}
Choosing the Right Approach
Using a loop is more intuitive and easier to understand for beginners. However, the formula is more efficient, especially for large values of n.