Sure, recursion in C language refers to a programming technique where a function calls itself directly or indirectly to solve a problem. Here's a simple explanation with an example:
Let's consider a classic example of recursion: calculating the factorial of a non-negative integer.
#include <stdio.h>
// Function to calculate factorial using recursion
int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: factorial of n = n * factorial of (n-1)
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
// Calling the factorial function
int fact = factorial(num);
printf("Factorial of %d is %d\n", num, fact);
return 0;
}
In this example, the factorial
function is defined to calculate the factorial of a non-negative integer n
.
n
is 0 or 1 because the factorial of 0 and 1 is 1.n
is greater than 1, the function calls itself with the argument (n - 1)
and multiplies the result by n
.When you run this program and input a non-negative integer, it calculates and prints its factorial using recursion. For example, if you input 5, it will calculate and print 5! = 5 * 4 * 3 * 2 * 1 = 120
.