Friday, July 29, 2016

C Basics - Recursion in C

C allows calling a function inside the same function, i.e., a function to call itself. This is called a recursive call of the function. The following example shows a function call itself.

void recursion() {
   recursion(); /* function calls itself */
}

int main() {
   recursion();
}

While using recursion, programmers need to be careful to define an exit condition from the function; otherwise it will go into an infinite loop.
Example: Program to find factorial of a given number.

#include <stdio.h>

long factorial(unsigned int i) {
   if(i <= 1) {
      return 1;
   }
   return i * factorial(i - 1);
}

int  main() {
   int i;
   long fact;
   printf("Enter a number:");
   scanf("%d", &i);
   fact = factorial(i);
   printf("Factorial of %d is %d\n", i, fact);
   return 0;
}
Output of above program,

Enter a number:4
Factorial of 4 is 24



Related topics:
Functions in C   |   Function Definition and Declaration in C   |   Calling a Function in C   |   Variable Arguments in C   |   Command Line Arguments in C

List of topics: C Programming

No comments:

Post a Comment