SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Recursion
Exercise:
Programming Exercises
Question:6 | ISBN:9780132576376 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.