Write a recursive code to find the sum of all elements of a list.

def sum(array,size):
  if(size==0):
     return 0
  else:
     size=size-1
     result=array[size]+sum(array,size)
  return result

#start of program
array=[1,2,3,2,3]
size=len(array) #size of array
result=sum(array,size) #call to function
print('sum of array is ',result)

 

Explanation: We are taking a list of integers, after that we are getting size of array(no of elements). result variable is storing the result of addition of numbers in the list. sum function is defined in the code which takes 2 arguments pointer to the list and number of elements.

if list has no elements 0 value is returned to result variable in main program. other wise we are decreasing size value each time function is called. this is a example of recursive function. result variable(local) of sum function will take calculated sum of elements. sum function is calling itself with size variable pointing to elements index in backward direction. this way we are adding every element.

All elements are adding in memory stack and are being assigned to result variable. when size has 0 value program adds 0 to calculated sum value provided by result variable in function. result variable in main program will get that value. finally we are printing sum.