Recursion is simple to understand: see "recursion" and it'll all be clear!

Your function calls itself with different parameters, and return to itself with the value each time when it's calculated.

Look at what happens with your code when you pass specific values: a == 2, b == 3

1) 2, 3 : b is not 1, so you call the function again, with a == 2, b == 2

1.1) 2, 2 : b is not 1, so you call the function again, with a == 2, b == 1

1.1.1) 2, 1 : b is one, so you return a: 2

1.2) returns to 2, 2: and returns the 2 you got from 1.1.1, plus 2 : 4

2) returns to 2, 3: and returns the 4 you got from 1.2, plus 2 : 6

So the whole function returns 6.

It's a poor example of recursion - a loop is a lot easier and more efficient - but just follow it through with a debugger, and you'll see what I mean.

14,028,229 members

Email

Password

Sign in with