Program to Find the Sum of Numbers in a Given Range in Java
Sum of Numbers in a Given Range
Given two integer inputs num1 and num2, the objective is to find the sum of all numbers in the given range using Java programming.
We will explore different methods to achieve this.
Method 1: Using a for Loop
We iterate from num1 to num2, adding each number to a sum variable.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the starting number: "); int num1 = scanner.nextInt(); System.out.print("Enter the ending number: "); int num2 = scanner.nextInt(); int sum = 0; for (int i = num1; i <= num2; i++) { sum += i; } System.out.println("Sum of numbers in given range: " + sum); scanner.close(); } }
Output:
Enter the starting number: 2 Enter the ending number: 4 Sum of numbers in given range: 9
Method 2: Using the Formula
We use the formula for the sum of the first n natural numbers: sum = n(n+1)/2
. Using this, we derive:
sum = (num2 * (num2 + 1) / 2) - ((num1 - 1) * num1 / 2)
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the starting number: "); int num1 = scanner.nextInt(); System.out.print("Enter the ending number: "); int num2 = scanner.nextInt(); int sum = (num2 * (num2 + 1) / 2) - ((num1 - 1) * num1 / 2); System.out.println("Sum of numbers in given range: " + sum); scanner.close(); } }
Output:
Enter the starting number: 2 Enter the ending number: 4 Sum of numbers in given range: 9
Method 3: Using Recursion
We use recursion to sum numbers from num1 to num2.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the starting number: "); int num1 = scanner.nextInt(); System.out.print("Enter the ending number: "); int num2 = scanner.nextInt(); System.out.println("Sum of numbers in given range: " + getSum(num1, num2)); scanner.close(); } static int getSum(int num1, int num2) { if (num1 > num2) { return 0; } return num1 + getSum(num1 + 1, num2); } }
Output:
Enter the starting number: 2 Enter the ending number: 4 Sum of numbers in given range: 9