Factorial program in C++
In this post, you will learn how to find the factorial of a number using the C++ programming language.
The factorial is normally used in different areas of mathematics, including algebra, mathematical analysis, and Combinations and Permutations. The factorial of a number n is denoted by n!. This is the product of all positive numbers less than or equal to n. It is calculated as-
n! = n X (n-1) X (n-3) X ……… X 3 X 2 X 1
Example of factorial
Suppose we want to get a factorial of 7, then the factorial will be.
7! = 7 X 6 X 5 X 4 X 3 X 2 X 1
5040
Factorial program in C++ using For Loop
In the given C++ program, we have used the for loop to iterate through all numbers between 1 and the given number 9, and getting the product of each number.
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,num;
cout<<"Enter any number: ";
cin>>num;
for(i=1;i<=num;i++){
fact=fact*i;
}
cout<<"Factorial of " <<num<<": "<<fact<<endl;
return 0;
}
Output of the above code:
Enter any number: 9
Factorial of 9: 362880
Factorial program in C++ using Recursion
Here is the C++ program to find the factorial of a number using the recursion function. Recursion function is a function which is called by itself. If the number equals to the 0, it returns 1. The factorial of a number less than equals to 0 does not exist. If the number is greater than 1, the function calls recursively and finds the factorial of a number.
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1);
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output of the above code:
Enter any number: 8
Factorial of a number: 40320
Related Articles
Queue implementation in c++Queue using linked list c++
Swapping of two numbers in C++
Generate random numbers in C++
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative