Recursion is the process of calling a function from another function. This method gives you a way to break down hard problems into smaller, simpler ones that are easier to solve. Recursion is not always easy to understand. Experimenting with it is the best way to figure out how it works.
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
Just like loops can get stuck in an endless loop, recursive functions can get stuck in an endless recursion. When a function keeps calling itself over and over, this is called "infinite recursion." Every recursive function should have a stopping condition, which is when the function stops calling itself. In the last example, the stopping point is when the parameter k equals 0.
To better understand the idea, it helps to see a lot of different examples. In this case, the function adds all the numbers between a start number and an end number. This recursive function will stop when end is not greater than start:
When using recursion, the developer should be very careful because it is easy to write a function that never ends or that uses too much memory or processor power. But if it's done right, recursion can be a very efficient and mathematically elegant way to write code.