function factorial program in cpp 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: program to calculate factorial of number in c++
#include <iostream>
using namespace std;
int main()
{
unsigned int n;
unsigned long long factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;
for(int i = 1; i <=n; ++i)
{
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
return 0;
}
Example 3: factorial c++ without using function
#include <iostream>
using namespace std;
int main()
{
unsigned int num;
unsigned long long factorial = 1;
cout << "Give me any positive number : ";
cin >> num;
for (int i = 1; i <= num; i++) {
factorial = factorial * i;
}
cout << "Factorial of the given number is: " << factorial;
}