For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. Use while statements in each of the following:

The factorial of a nonnegative integer n is written n! (pronounced “n factorial”)
and is defined as follows:
n! = n · (n – 1) · (n – 2) · ... · 1 (for values of n greater than 1)
and
n! = 1 (for n = 0 or n = 1).

a) Write a program that reads a nonnegative integer and computes and prints its factorial.
b) Write a program that estimates the value of the mathematical constant e by using the formula:
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).


a) ```
// Compute and print the factorial of the specified value.
#include
using namespace std;

int main()
{
int number; // user input
int factorial = 1; // factorial of input value

// get input
cout << "Enter a positive Integer: ";
cin >> number;

cout << number << "! is ";

while ( number > 0 ) // calculate factorial
{
factorial *= number;
number--;
} // end while

cout << factorial << endl;
} // end main
```
Enter a positive Integer: 5
5! is 120
b) ```
// Estimate the value of e to the specified accuracy.
#include
using namespace std;

int main()
{
int number = 1; // counter
int accuracy; // accuracy of estimate
int factorial = 1; // value of factorial
double e = 1.0; // estimate value of e

// get accuracy
cout << "Enter desired accuracy of e: ";
cin >> accuracy;

// calculate estimation
while ( number < accuracy )
{
factorial *= number;
e += 1.0 / factorial;
number++;
} // end while

cout << "e is " << e << endl;
} // end main
```

Computer Science & Information Technology

You might also like to view...

Once you have made a selection, you can click the ____________________ button on the options bar to further refine a selection.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology

The management group that has a high need for historical data along with information that allows prediction of future events is:

A) operations management. B) middle management. C) strategic management. D) virtual management.

Computer Science & Information Technology

The transactions T and U at the server are defined as follows:

T: x= read (i); write(j, 44);
U: write(i, 55);write(j, 66);
Initial values of ai and aj are 10 and 20. Which of the following interleavings are serially equivalent and which could occur with two-phase locking?

Computer Science & Information Technology

A(n) ________ refers to a cell with a fixed position in the worksheet

Fill in the blank(s) with correct word

Computer Science & Information Technology