Recursion in C++
Our example demonstrates recursive functions using a classic factorial calculation and a Fibonacci sequence generator.
To compile and run the program:
This example demonstrates two types of recursive functions in C++:
- A traditional recursive function (
fact
) that calculates the factorial of a given number. - A recursive lambda function (
fib
) that calculates the Fibonacci sequence.
The fact
function is straightforward: it calls itself with n-1
until it reaches the base case of n == 0
.
The fib
lambda is more complex. In C++, for a lambda to be recursive, we need to use std::function
to declare it before defining it. This allows the lambda to refer to itself within its own body.
Both functions demonstrate how recursive algorithms can be implemented in C++, showcasing the language’s support for this powerful programming concept.