C program to find factorial using function
- Home
- Calculations
- C program to find factorial using function
- On
- By
- 0 Comment
- Categories: Calculations, Find elements
C program to find factorial using function
C program to find factorial using function
In this tutorial, we will discuss the concept of C program to find factorial using function
Factorial is a product of all positive descending integer begins with a specified number (n) and calculates up to one
Example
factorial of 5 is
5!=5*4*3*2*1=120
factorial of 4 is
4!=4*3*2*1=24
The factorial of a positive number n is given below
factorial of n is
n!=n*(n-1)*....2*1
There are many ways to calculate a factorial using C programming language. Some of them are described as follows.
The user can provide numbers as they wish and get the factorial according to their input
C program to find factorial of a number using method
Program 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int factorial(int);
int num;
printf("Enter the number to find factorial\n");
factorial(num);//call the function
getch();
return 0;
}
int factorial(num){ //create function to find factorial
int i,fact=1; //declare variables
scanf("%d",&num);//get input from user
for(i=1; i<=num; i++)
{
fact=fact*i;//calculate factorial }
}
printf("Factorial of given number is: %d\n",fact);
}
When the above code is executed, it produces the following results
Enter a number for find factorial 6 Factorial of the 6 is : 720
C program to find factorial of a number using the function with return
Program 2
#include <stdio.h>
#include <stdlib.h>
int factorial(int);
int main()
{
int num,fact=1;
printf("Enter the number to find factorial\n");
scanf("%d",&num);//get input from user
printf("Factorial of %d is: %d\n",num,factorial(num));
//call the factorial function to display
getch();
return 0;
}
int factorial(int num){ //create function to find factorial
int i,fact=1; //declare variables
for(i=1; i<=num; i++)
fact=fact*i;//calculate factorial
return(fact); //return fact to main
}
When the above code is executed, it produces the following results
Enter a number for find factorial 5 Factorial of the 6 is : 120
C program to find factorial of a number using Ternary operator
Program 3
#include <stdio.h>
#include <stdlib.h>
int factorial(int n)//user defined method to calculate factorial
{
return(n==1 || n==0) ? 1: n*factorial(n-1);//calculate factorial using ternary operator
}
int main()
{
int num;
printf("Enter the number to find factorial\n");
scanf("%d",&num);//get input from user
printf("factorial of %d is %d\n",num,factorial(num));
//display factorial of given number
getch();
return 0;
}
When the above code is executed, it produces the following results
Enter the number to find factorial 7 Factorialof 7 is 5040
Suggested for you
Java code to find factorial of a number
Java code to find factorial of a number using Java method
Find factorial of a number in C
Find factorial of a number in CPP
Find factorial of a number in Python