Program to find the sum of numbers in a given range in Java

Sum of numbers in a given range :


In this article we will perform addition on natural numbers in a given range. So for this, we have to ask the user to enter two numbers which will denote the starting and ending of the range for adding all natural numbers between that range.

 

For better understanding let’s suppose two values 3 and 8,

Then, Sum of all natural numbers between 3 and 8 will be (3+4+5+6+7+8) = 33.

 

So we create a java program to calculate the sum of all natural numbers in a given range.

Sum of numbers in a given range using java

Working :

Step 1 : Ask the user to enter two numbers which will denote the starting and ending of the range for adding all natural numbers between that range.

Step 2 : Declare a variable to store the addition and initialize it with 0.

Step 3 : Use a loop to perform iterations for adding all natural numbers from starting range to the ending range.

Step 4 : Use a statement for addition purpose.

Step 5 : Print the result.

Code in Java :

//Java program to print the sum of numbers in a given range
import java.util.Scanner;
public class sum_of_numbers_in_range
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter starting number : ");
int start = sc.nextInt();
System.out.print("Enter ending number : ");
int end = sc.nextInt();
//declare a variable to store sum
int sum = 0;
//loop to add n natural numbers
for(int i = start ; i <= end ; i++)
sum=sum+i;
//display the sum
System.out.print("Sum of numbers in the range from "+start+" to "+end+" is "+sum);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter starting number : 1

Enter ending number : 5

Sum of numbers in the range from 1 to 5 is 15



Enter starting number : 2

Enter ending number : 14

Sum of numbers in range 2 to 14 is 104