C++ Program to find factorial of Number

 C++ Program to find factorial of Number 

 Find factorial of  a Number in C++

Program to find factorial of Number in C++

What is a Factorial of a number ‘n’?

The factorial of a number ‘n’ is the product of all number from 1 upto the number ‘n’

it is denoted by n!. 

For example:

4! = 4*3*2*1 = 24  

6! = 6*5*4*3*2*1 = 720    

C++ programs:

C++ Program to find factorial of Number  C++ programs, code c++, dev c++, c++ online, c language


Source code:

#include<iostream>
/*  iostream provides basic
input and output services for C++ programs */
using namespace std;
int main()
// Th execution of program start with the main function 
 {
    int num,factorial=1;
//Variable Declarations specify the type followed by the name
//Initialization is the process of assign the value to a variable
   cout<<" Enter Number To Find Its Factorial:  ";
// cout is used to display the same statement in the output.
    cin>>num;
// cin is used to enter the value by the user.
    if (num < 0)
/* The if/else statement executes a block
 of code if a specified condition is true. 
If the condition is false, another block 
of code can be executed*/
   cout << "Error! Factorial of a negative number doesn't exist.";
    else {
    for (int a=1;a<=num;a++)
    // for loop
     {
        factorial=factorial*a;
    }
    cout<<"Factorial of " <<num <<" is :"<<factorial<<endl;
    return 0;
}   
}




In this program, we take a positive integer from the user and compute the factorial using for loop. We print an error message if the user enters a negative number.
When the user enters a positive integer  for loop is executed and computes the factorial. The value of a is initially 1.
The program runs until the statement a <= num becomes false.
































































Post a Comment

0 Comments