Here is a program in C to calculate the factorial value of an integer.
The factorial of a number is the product of all the integers between 1 and that number. For example factorial of 5 is 5*4*3*2*1. This can also be expressed as 5!=5*4!, where ‘!’ stands for factorial.
Hence factorial of a number can also be programmed using recursion. Here I have given two methods for calculating factorial of a number, using non-recursive function and using recursive function.
Non-recursive function for calculating the factorial value of an integer
Steps:
- Declare prototype for the function named factorial() used to calculate factorial value.
- Declare two integers a and fact.
- Prompt the message to enter any number to calculate the factorial.
- Allow the user to enter number using scanf().
- Use function factorial() to calculate the factorial value and return that.
- Print the returned value to the screen using printf() command.
code:
#include <stdio.h> int factorial(int); int main() { int a, fact; printf("Enter any number"); scanf("%d",&a); fact=factorial(a); printf("Factorial value-%dn", fact); return 0; } int factorial(int x) { int f=1,i; for(i=x;i>=1; i--) f=f*i; return(f); }
Recursive function for calculating the factorial value of an integer
Steps:
- Declare prototype for the function named rec() used to calculate factorial value.
- Declare two integers a and fact.
- Prompt the message to enter any number to calculate the factorial.
- Allow the user to enter number using scanf().
- Use function rec() to calculate the factorial value using recursive method and return that.
- Print the returned value to the screen using printf() command.
code:
#include <stdio.h> int rec(int); int main() { int a, fact; printf("Enter any number"); scanf("%d",&a); fact=rec(a); printf("Factorial value-%dn", fact); return 0; } int rec(int x) { int f; if(x==1) return(1); else f=x*rec(x-1); return(f); }