1. Introduction
Natural numbers are the set of positive integers starting from 1 and increasing without bound. The sum of natural numbers can be calculated using a formula, but in this blog, we’ll see how to calculate it using a simple Java program. We will calculate the sum of the first n natural numbers, where n is a user-input value.
2. Program Steps
1. Declare a class named SumOfNaturalNumbers.
2. Inside this class, define the main method.
3. In the main method, create a Scanner object to read user input.
4. Prompt the user to enter a natural number n.
5. Declare a variable sum and initialize it to 0.
6. Create a loop to iterate from 1 to n.
7. In each iteration, add the loop variable to the sum.
8. After the loop ends, print the calculated sum.
3. Code Program
import java.util.Scanner; // Import Scanner class
public class SumOfNaturalNumbers { // Step 1: Declare a class named SumOfNaturalNumbers
public static void main(String[] args) { // Step 2: Define the main method
Scanner sc = new Scanner(System.in); // Step 3: Create Scanner object to read input
System.out.println("Enter a natural number n: "); // Step 4: Prompt the user to enter a natural number n
int n = sc.nextInt(); // Read the user input
int sum = 0; // Step 5: Declare and initialize sum to 0
// Step 6: Create a loop to iterate from 1 to n
for (int i = 1; i <= n; i++) {
sum += i; // Step 7: In each iteration, add the loop variable to the sum
}
// Step 8: Print the calculated sum
System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
}
}
Output:
Enter a natural number n: 10 The sum of the first 10 natural numbers is: 55
4. Step By Step Explanation
– Step 1: A class named SumOfNaturalNumbers is declared.
– Step 2: The main method is defined inside the SumOfNaturalNumbers class.
– Step 3: A Scanner object is created to read the user input.
– Step 4: The user is prompted to enter a natural number n.
– Step 5: A variable sum is declared and initialized to 0.
– Step 6: A for loop is created to iterate from 1 to n.
– Step 7: In each iteration of the loop, the loop variable i is added to the sum.
– Step 8: After the loop ends, the calculated sum of the first n natural numbers is printed to the console.