Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Recursion:

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.

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.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java