Thursday, 12 July 2012

Program to calculate factorial of a number using recursion in C


Sample Output -




Code -



/* 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 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 number)
{
if (number == 1) //__ Condition that will stop the infinite looping __
{
return 1;
}
else
{
return number * factorial (number - 1); //__ Recursion __
}
}

No comments:

Post a Comment