Answer to Question #100831 in C++ for zahra

Question #100831
Write a program that will display the result of n! using a loop. For example,if the user enters 5 for
n, the program should display “factorial of is 120”. solve with while
1
Expert's answer
2020-01-03T03:10:51-0500

/***************************************************************************************/

/** Example of a factorial function. */

/***************************************************************************************/


#include <iostream>


using namespace std;


int inputPosInt(string); //Input a positive integer with minimum verification.

unsigned long long factorial(int); //Function for calculating the factorial.


int main()

{

int d = inputPosInt("Please enter a positive integer: ");

unsigned long long l = factorial(d);


if(l == 0) //The function returns zero if the result is larger than ULLONG_MAX.

{

cout << "Too many to calculate factorial." << endl;

}

else

{

cout << "The factorial of " << d << " is " << l << endl;

}


return 0;

}


/******************************************/

/**Function for calculating the factorial.*/

/******************************************/

unsigned long long factorial(int d)

{

unsigned long long l = 1;


if(d == 0) return 1;

do

{

l*=d--;

if((d>0)&&((ULLONG_MAX/d)<l)) return 0; //Return zero if the result is larger than ULLONG_MAX

}while(d>0);


return l;

}



/** Function for entering a value of type "int" with validation. */

/** The string in the argument is needed to prompt for data entry. */

int inputPosInt(string s)

{

int d;

bool b;


do{

b = true;

cout << s;

cin >> d;

if(!cin) //If incorrect characters are entered, then clear the input buffer and ask to enter again.

{

cout << "The input is not correct. Try again.\n";

cin.clear();

while (cin.get() != '\n');

}

else

{

if(d >= 0)

{

b = false;

}

else

{

cout << "The input is not correct. Try again.\n" << endl;

cin.clear();

while (cin.get() != '\n');

}

}

}while(b);


return d;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS