Sum of Numbers
Design a function that accepts an integer argument and returns the sum of all the integers
from 1 up to the number passed as an argument. For example, if 50 is passed as an
argument, the function will return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate
the sum.
Sum of Numbers using recursion function program code:
# Create a function name, calculateSum that accepts an integer argument
# and returns the sum of all the integers from 1 up to the number passed as an argument.
def calculateSum(n):
if n == 1:
return 1
else:
#Recursive call, calculateSum
return n + calculateSum(n - 1)
#Prompt and read the input number from the user
number = int(input("Enter a positive integer: "))
#Call the function, calculateSum
totalSum = calculateSum(number)
print("Sum of integers from 1 to", number, ":", totalSum)
Executed Output 1:
Enter a positive integer: 50
Sum of integers from 1 to 50 : 1275
Executed Output 2:
Enter a positive integer: 2
Sum of integers from 1 to 2 : 3