Program to Find the Sum of Numbers in a Given Range in Python
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 Python 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.
num1 = int(input("Enter the starting number: ")) num2 = int(input("Enter the ending number: ")) sum = 0 for i in range(num1, num2 + 1): sum += i print("Sum of numbers in given range:", sum)
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)
num1 = int(input("Enter the starting number: ")) num2 = int(input("Enter the ending number: ")) sum = (num2 * (num2 + 1) // 2) - ((num1 - 1) * num1 // 2) print("Sum of numbers in given range:", sum)
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.
def get_sum(num1, num2): if num1 > num2: return 0 return num1 + get_sum(num1 + 1, num2) num1 = int(input("Enter the starting number: ")) num2 = int(input("Enter the ending number: ")) print("Sum of numbers in given range:", get_sum(num1, num2))
Output:
Enter the starting number: 2 Enter the ending number: 4 Sum of numbers in given range: 9