Learning Sections show
Recursion in C
Example
#include<stdio.h> // Include the standard input-output library
// Function declaration
int factorial(int n);
int main() {
// Variable declaration
int num = 5;
int result;
// Function call
result = factorial(num);
// Print the result
printf("Factorial of %d is %d\n", num, result);
return 0;
}
// Function definition
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
Explanation:
Recursion in C is a process where a function calls itself directly or indirectly, allowing it to perform repeated tasks.
In this example:
#include<stdio.h>: Includes the standard input-output library which allows us to use theprintffunction.int factorial(int n);: Declaration of the functionfactorial, which takes an integer argument and returns an integer.int main(): The main function where the program execution begins.result = factorial(num);: Calls thefactorialfunction with argument 5, and stores the return value in the variableresult.printf("Factorial of %d is %d\n", num, result);: Prints the result to the console.int factorial(int n): Definition of thefactorialfunction.if (n == 0) { return 1; }: Base case that ends the recursion whennis 0.else { return n * factorial(n - 1); }: Recursive call that continues to calculate the factorial by calling itself withn - 1.return 0;: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.
In summary, recursion in C allows functions to call themselves to solve problems that can be broken down into smaller, similar sub-problems. The key to a recursive function is the base case, which stops the recursion, and the recursive case, which continues the process.