Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Calculate the Sum of Natural Numbers


In this article, we will understand how to calculate the sum of natural numbers in Java. All possible positive numbers from 1 to infinity are called natural numbers.

Below is a demonstration of the same −

Input

Suppose our input is −

50 and 100

Output

The desired output would be −

Sum of natural numbers from 50 to 100 is 3825

Algorithm

Step1- Start
Step 2- Declare three integers my_lower_limit , my_upper_limit, sum.
Step 3- Prompt the user to enter two integer value/ define the integers
Step 4- Read the values
Step 5- Run a for-loop, add the number with its next number until the upper limit is reached.
Store the sum in a variable.
Step 6- Display the result
Step 7- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool Java Program to Calculate the Sum of Natural Numbers.

import java.util.Scanner;
public class NaturalNumbersSum {
   public static void main(String[] args) {
      int my_lower_limit , my_upper_limit, sum;
      System.out.println("Required packages have been imported");
      Scanner scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.print("Enter the starting number: ");
      my_lower_limit = scanner.nextInt();
      System.out.print("Enter the max number: ");
      my_upper_limit = scanner.nextInt();
      sum = 0;
      for(int i = my_lower_limit; i <= my_upper_limit; ++i){
         sum += i;
      }
      System.out.println("The sum of natural numbers from " + my_lower_limit + " to " + my_upper_limit + " is " +sum);
   }
}

Output

Required packages have been imported
A scanner object has been defined
Enter the starting number: 50
Enter the max number: 100
The sum of natural numbers from 50 to 100 is 3825

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class NaturalNumbersSum {
   public static void main(String[] args) {
      int my_input_1 , my_input_2, sum;
      my_input_1 = 50;
      my_input_2 = 100;
      sum = 0;
      System.out.println("The first and last numbers are defined as " +my_input_1 +" and "+my_input_2 );
      for(int i = my_input_1; i <= my_input_2; ++i){
         sum += i;
      }
      System.out.println("The sum of natural numbers from " + my_input_1 + " to " + my_input_2 + " is " +sum);
   }
}

Output

The first and last numbers are defined as 50 and 100
The sum of natural numbers from 50 to 100 is 3825