factorial program in c code example
Example 1: factorial in c++
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
int fact(int i){
if (i <= 1) return 1;
else return i*fact(i-1);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
cout << fact(N) << "\n";
return 0;
}
Example 2: factorial c program using for loop
#include<stdio.h>
int main(){
int i,f=1,num;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
f=f*i;
printf("Factorial of %d is: %d",num,f);
return 0;
}
Example 3: factorial of a given number in c
#include <stdio.h>
long int factorialOf(int number){
long int factorial = 1;
while(number){
factorial*=number;
number-=1;
}
return factorial;
}
int main(void) {
int n;
printf("Find factorial of \n");
scanf("%d",&n);
printf("\nThe factorial of %d is %ld",n,factorialOf(n));
return 0;
}
Example 4: c code factorial function
#include <stdio.h>
int fact(int);
void main()
{
int no,factorial;
printf("Enter a number to calculate it's factorial\n");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial of the num(%d) = %d\n",no,factorial);
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}