Saturday 18 August 2012

Factorial of a number using Recursion


/* Program to calculate Factorial of a number using Recursion */

/* Recursion is a programming technique that allows the programmer to express operations in terms of themselves.
      
   In C/C++, this takes the form of a function that calls itself. */

#include<stdio.h>

#include<conio.h>

int factorial(int temp_number);

int main()
{
       int number = 0, result = 0;

       printf("\n\n\t __ Program to calculate the factorial of a number using Recursion __");

       printf("\n\n\n  Enter the Number - ");

       scanf("%d",&number);

       result = factorial(number);

       printf("\n\n\t Factorial of %d = %d",number, result);

       getch();

       return 0;

       /*___ return 0 tells the compiler that program has executed
      
              successfully without any error */
}

int factorial(int temp_number)
{
       int result_factorial = 0;

       if (temp_number == 1)      //__ Condition that will stop the infinite looping __
       {
              return 1;
       }
       else
       {
              result_factorial =  temp_number * factorial (temp_number - 1);       //__ Recursion __
               
              return result_factorial;
       }
}

No comments:

Post a Comment