Java Program to Calculate the Sum of Natural Numbers

This program calculates the sum of the first ( N ) natural numbers using the formula ( \text{Sum} = \frac{N \times (N + 1)}{2} ).

import java.util.Scanner;

public class SumOfNaturalNumbers {

    // Method to calculate the sum of the first N natural numbers
    public static int sumOfNaturalNumbers(int N) {
        // Using the formula: Sum = N * (N + 1) / 2
        return N * (N + 1) / 2;
    }

    // Main method
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input: User enters the value of N
        System.out.print("Enter the value of N: ");
        int N = scanner.nextInt();

        // Calculate the sum using the method
        int sum = sumOfNaturalNumbers(N);

        // Output: Display the result
        System.out.println("The sum of the first " + N + " natural numbers is: " + sum);
    }
}

Code Breakdown

1. Import Statement

  • Line: import java.util.Scanner;
  • This line imports the Scanner class from the java.util package to get user input.

2. Class Declaration

  • Line: public class SumOfNaturalNumbers {
  • This line declares a public class named SumOfNaturalNumbers.

3. Method to Calculate the Sum

  • Line: public static int sumOfNaturalNumbers(int N) {
  • This method calculates the sum of the first ( N ) natural numbers and returns an integer.

4. Sum Calculation

return N * (N + 1) / 2;
  • This line uses the formula to calculate the sum of the first ( N ) natural numbers.

Main Method

5. Create Scanner Object

  • Line: Scanner scanner = new Scanner(System.in);
  • This creates a Scanner object for reading user input.

6. User Input

System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
  • Prompts the user for input and reads it into the variable N.

7. Calculate the Sum

  • Line: int sum = sumOfNaturalNumbers(N);
  • Calls the sumOfNaturalNumbers method with the user’s input.

8. Display the Result

System.out.println("The sum of the first " + N + " natural numbers is: " + sum);
  • Displays the calculated sum to the user.

Conclusion

This program effectively calculates the sum of the first ( N ) natural numbers using a straightforward mathematical formula. It demonstrates fundamental programming concepts like methods, user input, and output. If you have any questions or need clarification on any part, feel free to ask!



0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *