Recursion
Recursion function is a powerful programming technique or method in C language where a function declared in a C program calls itself directly or indirectly to solve a larger problem by referring to a smaller example model of the same function problem. In C language, the use of recursion function is particularly useful for subtasks that are solved by dividing a complex or large program project into smaller, similar sub-problems or smaller modules.
Example of Recursive Function in C.
An example of a general recursion is calculating the factorial numbers of a number (n!), which is solved in this way in the function.
num! = num * (num-1) * (num-2) * … * 1
Here 0! is defined as 1.
Find factorial using recursion in C program.
#include <stdio.h>
// Function declaration
unsigned int fact(unsigned int num);
// Function definition
unsigned int fact(unsigned int num) {
//when factorial num is 0
if (num == 0) {
return 1;
}
// count factorial of num is num * fact(num-1)
otherwise {
return num * fact(num – 1);
}
}
int main() {
unsigned int decimal = 7;
unsigned int output = fact(decimal);
printf(“\n Factorial is – %u is %u”, decimal, output);
return 0;
}