Recursion is a powerful programming technique where a function calls itself to solve smaller instances of a problem. It is widely used in C programming for tasks that can be broken down into similar subtasks, such as sorting, searching, and calculating mathematical sequences.. In this article, we are going to discuss recursion in c and will see one example of recursion.
Getting Started
In simple terms, recursion is when a function calls itself, either directly or indirectly. This self-referential approach allows problems to be solved more elegantly and with less code compared to iterative methods in certain scenarios.
Each recursive function must have:- Base Case – A condition under which the recursion ends.
- Recursive Case – The part of the function that calls itself with a reduced or simpler problem.
returnType functionName(parameters) {
if (base_condition) {
// Base case: stop recursion
return result;
} else {
// Recursive case: call the function again
return functionName(modified_parameters);
}
}
The number of recursive calls is limited to the size of the stack. Each time the function is called, new storage is allocated for the parameters and for the auto and register variables so that their values in previous, unfinished calls are not overwritten. Parameters are only directly accessible to the instance of the function in which they are created. Previous parameters are not directly accessible to ensuing instances of the function.
A function that has to be called recursively must be declared not-void type. If a function is declared as void, then it can’t be defined as a recursive function.
Note that variables declared with static storage do not require new storage with each recursive call. Their storage exists for the lifetime of the program. Each reference to such a variable accesses the same storage area.
Recursion Examples
This example illustrates recursive calls: Where it accept a number and displays it factorials. # include <stdio.h>
# include <conio.h>
int factorial( int num );/* Function prototype */
int main()
{
int result, number;
chrscr();
printf("\n Enter a number whose factorial you want.");
scanf("%d", & number);
printf("\n Factorial of %d=%d", number, factorial(number));
getch();
}
int factorial( int num ) /* Function definition */
{
if (num ==0)
return (1);
else
return( num * factorial( num - 1 ) );
}
Summary
Recursion is a foundational concept in C programming that helps solve complex problems in an elegant and concise way. However, it should be used judiciously, considering both the strengths and limitations. Mastering recursion can significantly improve your problem-solving skills and deepen your understanding of algorithms and data structures.
Thanks