Recursive Function in C - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Recursive Function in C

Share This


At the beginning of the tutorial, we discussed functions in detail. In this section, we will discuss a special type of function, where a function needs to be called from within itself. This type of function is known as a recursive function.

To understand the recursive function, here the same example (program to calculate factorial using a loop) is being used.

At this stage, it will be difficult to understand the difference between recursive function and iteration. There are some problems, where we prefer recursion and sometimes recursion is avoided.

Moreover, remember that there are many problems in computer science and engineering that can not be solved without recursive functions.
Factorial using Recursion
#include<stdio.h> int fact(int n); int main(void) { int n, res; printf("Factorial using recusion"); printf("Enter a number : "); scanf("%d", &n); res = fact (n); printf("Factorial of %d is %d\n", n, res); return 0; } int fact (int n) { if (n < 1) return 1; else return n * fact (n-1); }


For a very simple problem like the calculation of factorial, we should avoid recursion. It consumes more time and more memory.

This topic will be discussed in the Data Structure tutorial.
Fibonacci using recursion
#include <stdio.h> float fib (float m); int main() { float i, n, fibonacci; printf ("Enter the number of terms for the series : "); scanf("%f", &n); printf("\n"); for(i = 1; i <= n; i++) { fibonacci = fib(i); printf("%6.0f", fibonacci); } return 0; } float fib(float m) { float fibonacci; if (m < 2) return 1; else fibonacci = fib(m - 1) + fib(m - 2); return(fibonacci); }


GCD using recursion
#include<stdio.h> #include<process.h> int gcd(int, int); int main() { int x, y; printf("\n Enter the values of X & Y respectively : "); scanf("%d%d", &x, &y); gcd(y, x); return 0; } int gcd(int a, int b) { a = a % b; if (!a) { printf("\n\n The requirde value is : %d", b); exit(1); } gcd(b, a); return 0; }

Recursion of the main function in C


We know that the recursive function calls itself. What will happen if you want to call the main function recursively? Is it applicable to the main function?
Recursive main() function
#include<stdio.h> int main() { static int i = 1; if (i <= 10) { printf("%d ", i++); main(); } }
Output: 1 2 3 4 5 6 7 8 9 10



Happy Exploring!

No comments:

Post a Comment