Home Lifestyle Sum of N Natural Numbers in Java Language

Sum of N Natural Numbers in Java Language


Sum of N Natural Numbers in Java Language – We have to develop a Java program to calculate the sum of n natural numbers. Sum of natural number N as given as sum = 1+2+3+….+N

  • Examples:-
  • 1+2+3+4+5 = 15
  • 1+2+3+4+5+6+7+8+9+10 = 55

<img decoding=

import java.util.Scanner;

public class NaturalNumberSum {

  // method to find sum of N natural numbers
  public static int naturalNumberSum(int number){

     int i = 1; // iterator variable
     // variable to store sum value
     int sum = 0;

     // loop to repeat the process
     while (i<=number) {

        // add into sum value
        sum = sum + i;
        // increase iterator variable

     // return sum value
     return sum;

  public static void main(String[] args) {

     // declare variables
     int number = 0;
     int sum = 0;

     // create Scanner class object
     Scanner scan = new Scanner(System.in);

     // read input
     System.out.print("Enter N value:: ");
     number = scan.nextInt();

     // Calculate the sum value
     sum = naturalNumberSum(number);

     // display result
     System.out.println("Sum = "+sum);

     // close Scanner class objects

The output for different test-cases:-

Enter N value:: 5
Sum = 15

Enter N value:: 10
Sum = 55

Types of Sorting Algorithms:

Additional Reading


If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

Thank you 😊 Keep Learning !

Previous articleSum of Digits of a Number in Java Program
Next articleFind Sum of Even Digits in a Given Number in Java Program


Please enter your comment!
Please enter your name here