#include // Write a program that queries the user for an // integer 'n' and then prints n!. // // If n < 0, simply return 0. Otherwise, // // 0! = 1! = 1 // // and, for n >= 2, // // n! = n*(n - 1)*(n - 2)*...*3*2*1. // // For example, // // 5! = 5*4*3*2*1 = 120. // // Scroll down for a hint first, and then for // two possible solutions. // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; std::cout << n << "! = " << 1 << std::endl; return 0; } // Hint: // // Create a local variable that stores the // value of the product. Then multiply that // variable by each integer from 1 through 'n'. // // What should the initial value of that local // variable be? // // Recall that when accumulating a sum, we // normally begin with 0. When accumulating a // product, what value should we begin with? // // Also consider what happens when n == 0. // The loop should execute zero times, but the // result must still be 1. // Here is one solution, multiplying upward // from 1 through 'n': /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int factorial{ 1 }; for ( int k{ 1 }; k <= n; ++k ) { factorial *= k; } std::cout << n << "! = " << factorial << std::endl; return 0; } */ // Here is another solution, multiplying downward // from 'n' through 1: /* int main() { int n{}; std::cout << "Enter an integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int factorial{ 1 }; for ( int k{ n }; k >= 1; --k ) { factorial *= k; } std::cout << n << "! = " << factorial << std::endl; return 0; } */