How these recursion works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How these recursion works?

hey, can anyone explain to me how these recursion works? def Sum(n): if n == 0 s=0 print (s) else: s=n+Sum(n-1) return s print Sum(10) many thanks :)

2nd Jul 2018, 4:31 PM
Sal
4 Answers
0
Recursion is when one function call itself. In this example first n = 10 then s = 10 + 9 + 8 ... while n = 0 and then it print(0).
2nd Jul 2018, 4:47 PM
B K
0
but s=n+Sum(n-1) means: I. 10+10-1= 19 II. 9+ 9 -1= 17 III. 8+ 8 -1=15 . . . .. right?
2nd Jul 2018, 5:05 PM
Sal
0
No, s=n+Sum(n-1) means: I. 10+sum(10-1)(function Sum(9)(with 9 as argument) will again run) II. 10+ 9 +sum(9-1)= III. 10+9+8+sum(8-1) . . . ..
2nd Jul 2018, 5:08 PM
Pulkit Kamboj
Pulkit Kamboj - avatar
0
aah i understand. thanks a lot
2nd Jul 2018, 6:16 PM
Sal