Recursion
Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion is Recursion.
Recursion
Recursion is a powerful concept where a function calls itself to solve a problem. It’s useful for tasks that can be broken down into smaller, similar tasks.
How Recursion Works:
Base Case: The simplest case, where the function returns a result without making any further recursive calls.
Recursive Case: The function calls itself with modified arguments, moving towards the base case.
Example: Factorial Function (Recursive)
We already saw a recursive factorial function, but let’s break it down:
Explanation:
Base Case: When
n
is0
, the function returns1
.Recursive Case: For any other
n
, the function multipliesn
by the factorial ofn-1
.
Example: Fibonacci Sequence (Recursive)
The Fibonacci sequence is a classic example of recursion.
Explanation:
Base Case: When
n
is0
or1
, returnn
.Recursive Case: Sum of the two preceding Fibonacci numbers.
Function Pointers
Function pointers are variables that store the address of a function. They allow you to call functions indirectly and are useful for callback functions and dynamic function dispatch.
Declaration and Usage:
Explanation:
void (*funcPtr)();
declares a function pointerfuncPtr
that points to a function returningvoid
and taking no arguments.funcPtr = greet;
assigns the address of thegreet
function tofuncPtr
.funcPtr();
calls thegreet
function using the pointer.
Inline Functions
An inline function is a function that is expanded in line where it is called, rather than being invoked through a function call. This can reduce the overhead of function calls.
Declaration:
Explanation:
Use the
inline
keyword before the function’s return type.The compiler tries to replace the function call with the function’s code to avoid the overhead of a call.
Recursive Functions with Multiple Base Cases
Sometimes, a recursive function may have multiple base cases.
Example: Greatest Common Divisor (GCD)
Explanation:
Base Case: When
b
is0
, returna
.Recursive Case: Compute GCD of
b
anda % b
.
Summary
Recursion involves functions calling themselves, useful for problems that can be broken down into smaller similar problems.
Function Pointers allow indirect function calls, useful for callbacks and dynamic dispatch.
Inline Functions can reduce the overhead of function calls by expanding the function’s code at the call site.
Functions can have multiple base cases in recursion.
Last updated
Was this helpful?