105k views
5 votes
Exercise 1. (Sum of Integers) Implement the functions sum_iter() and sum_rec() in sum_of_ints.py that take an integer n as argument and return the sum S(n) = 1 + 2 + 3 + · · · + n, computed iteratively (using a loop) and recursively. The recurrence equation for the latter implementation is

User Yrll
by
5.6k points

1 Answer

3 votes

Answer:

Step-by-step explanation:

We'll start out by prompting users to input an integer n. Then we create 2 functions to calculate the total, one by iteration and the other by recursion.

n = input('Please input an integer n')

def sum_iter(n):

total = 0

for i in range(n+1):

total += i

return total

sum_iter(n)

def sum_rec(n):

if n == 0:

return 0

else:

return n + sum_rec(n-1)

sum_rec(n)

User Kiser
by
5.3k points