Java Program to Find Sum of Natural Numbers

Natural numbers are a set of positive integers starting from 1, and they go like 1, 2, 3, 4, 5, ... and so on. Sometimes in programming, we come across a need to compute the sum of the first 'n' natural numbers. In this blog post, we will understand and create a Java program that does just that! 

The Mathematical Approach 

Mathematically, the sum of the first 'n' natural numbers can be found using a simple formula:

Sum=2n(n+1)

For example, if we want to find the sum of the first 5 natural numbers:

Sum=25(5+1)=15

Java Program to Find Sum of Natural Numbers

import java.util.Scanner;

public class NaturalNumberSum {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number up to which you want the sum:");
        int n = scanner.nextInt();

        int sum = calculateSum(n);
        System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
    }

    public static int calculateSum(int n) {
        return n * (n + 1) / 2;
    }
}

Output:

Enter the number up to which you want the sum:
100
The sum of the first 100 natural numbers is: 5050

Step by Step Explanation: 

User Input: 

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number up to which you want the sum:");
        int n = scanner.nextInt();

We are using Java's Scanner class to take user input. Here, we prompt the user to enter a number n up to which they want to calculate the sum. 

Function to Calculate Sum:

    public static int calculateSum(int n) {
        return n * (n + 1) / 2;
    }

This function takes in a number n and calculates the sum of the first n natural numbers using the formula mentioned above. 

Displaying the Result: 

        int sum = calculateSum(n);
        System.out.println("The sum of the first " + n + " natural numbers is: " + sum);

 We call our calculateSum function to get the sum and then display it to the user. 

Conclusion

Computing the sum of natural numbers is one of the basic mathematical operations that showcases the power of mathematical formulas in programming. This article offers a simple approach to implement this operation in Java. It serves as a foundational step for newcomers to understand how mathematical concepts and programming go hand in hand. Happy coding!

Comments