Monday, 1 May 2017

Calculate the factorial in C++ || C++ Sample Programs

Leave a Comment
Question::

Write a program that asks the user to enter an integer number. The main() program will pass this number to a function called “ fact()”. This function will return the factorial of the input value. Show the calculated factorial of the given number on the screen.

Code:

/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
#include<iostream>
using namespace std;

int fact(int); // prototype of a function

void main() {
       int number;
       cout << "Enter a Number to find its factorial == ";
       cin >> number;
       cout<<"Factorial of "<<number<<"is == "<<fact(number);
}


//Body of a function

//Logic of factorial is pretty simple that is if we have a number like 5 then the formula of factorial
//will be like this 5*4*3*2*1
int fact(int myFactorial) {
       int result = 1;
       for (int i = 1; i <=myFactorial; i++)
       {
              if (result == 1) {
                     result = result*i;
              }
              else
              {
                     result = result*i;
              }
       }
       return result;
}




Related Articles:

C++ Primer Plus Sixth Edition Complete Solution Manual 

C++ Books Solution

  

If You Enjoyed This, Take 5 Seconds To Share It

0 Questions: