Thursday, 11 July 2019

12th Prog-3 Write a recursive code to find the sum of all elements of a list in a python.

def sum_arr(arr,size):
   if (size == 0):
     return 0
   else:
     return arr[size-1] + sum_arr(arr,size-1)

#main program
n=int(input("Enter the number of elements for list:"))
a=[]
for i in range(0,n):
    element=int(input("Enter element:"))
    a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)


Output
Enter the number of elements for list:6
Enter element:2
Enter element:3
Enter element:5
Enter element:7
Enter element:9
Enter element:10
The list is:
[2, 3, 5, 7, 9, 10]
Sum of items in list:
36

No comments:

Post a Comment