0

The problem is add up all numbers from 1 to num. e.g: If the input is 4 then your program should return 10 because 1 + 2 + 3 + 4 = 10.

so this is my solution

def SimpleAdding(num):
  total = []
  for i in range(1,num+1):
    total.append(i)

 return sum(total)

and this is the top solution of the problem

def SimpleAdding(num): 
    if num == 1:
      return 1
    else:
      return num + SimpleAdding(num-1)

I wanna know how this kind of solution work without looping. It doesn't make sense to me at all. I'm just a beginner btw.

1 Answers1

1

here is diagram

enter image description here

def SimpleAdding(num): if num == 1: return 1 else: return num + SimpleAdding(num-1)

this is recursion

for SimpleAdding(5) this is happening :

1. 5 + SimpleAdding(4)
2. 5 + 4+ SimpleAdding(3) # recall again as no exit condition meet
3. 5+ 4+ 3 + SimpleAdding(2)
4. 5 + 4+ 3+ 2+ SimpleAdding(1)
5. 5+ 4 + 3+ 2+ 1 # finally giving 1 
sahasrara62
  • 10,069
  • 3
  • 29
  • 44