Write a C++ Program to print factorial of a number. How to print factorial of a number using C++ code.
Given an input number, we have to write a code to calculate a factorial of a number.
Factorial of a non-negative number n, is the product of all integers less than or equal to n.
For example - Factorial of 5 is 120.
5! = 5 * 4 * 3 * 2 * 1 = 120
C Program to Print Factorial of a Number
Java Program to Print Factorial of a Number
Print factorial of a number using recursion
Given an input number, we have to write a code to calculate a factorial of a number.
What is Factorial?
Factorial of a non-negative number n, is the product of all integers less than or equal to n.
For example - Factorial of 5 is 120.
5! = 5 * 4 * 3 * 2 * 1 = 120
C Program to Print Factorial of a Number
Java Program to Print Factorial of a Number
C++ Program to Print Factorial of a Number
#include<iostream.h> int main() { int num, fact=1; cout << "Enter a number: "; cin >> num; //If number is greater than zero if(num > 0) { for(int i=1; i <= num; i++){ fact = fact*i; } cout << "Factorial of a number is: "<< fact; } else if (num == 0 ){ cout << "Factorial of 0 is 1"; } else { cout << " Factorial of a negative number doesn't exist"; } return 0; }
C++ Program to Print Factorial of a Number using Function
#include <iostream> using namespace std; int factorial(int num) { int fact = 1; //Factorial of a zero is zero if (num == 0) { return 1; } for (int i = 1; i <= num; i++) { fact = fact*i; } return fact; } int main(void) { int num; cout << "Enter a number \n"; cin >> num; if (num >= 0) { //Function is called factorial(num) cout << "Factorial of a number is " << factorial(num); } else { cout << "Factorial of a negative number doesn't exist"; } return 0; }
C++ Program to Print Factorial of a Number Video Tutorial
Print factorial of a number using recursion
No comments:
Post a Comment