We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4
Recursive Function
In C programming, recursion is a technique where a function calls itself to
solve a problem.
Any function which calls itself is called recursive function, and such function calls are called recursive calls.
However, it is important to impose a termination condition of recursion.
Recursion code is shorter than iterative code.
A recursive function performs the tasks by dividing it into the subtasks.
There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function. Factorial of a Number using Recursion #include <stdio.h> int factorial(int); return 0; int main() { } int num; int factorial(int n) { printf("Enter a positive integer: "); if (n == 0 || n == 1) { scanf("%d", &num); return 1; } else { if (num < 0) { // Recursive call to calculate factorial printf("Factorial is not defined for for n-1 and multiply it with n negative numbers.\n"); return n * factorial(n - 1); } else { } int result = factorial(num); } printf("Factorial of %d is %d.\n", num, result); } Example of Fibonacci series using recursion #include <stdio.h> } int fibonacci(int); printf("\n"); } int main() { int n; return 0; printf("Enter the value of n: "); } scanf("%d", &n); int fibonacci(int n) { if (n == 0) { if (n < 0) { return 0; printf("Invalid input! n must be a non- } else if (n == 1) { negative integer.\n"); return 1; } else { } else { printf("Fibonacci series up to the %dth return fibonacci(n - 1) + fibonacci(n - 2); term:\n", n); for (int i = 0; i < n; i++) { } printf("%d ", fibonacci(i)); }