Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ Program The mathematical function of \"factorial\" applied to positi

ID: 674672 • Letter: W

Question

Write a C++ Program

The mathematical function of "factorial" applied to positive integers involves multiplication, possible a lot of it!

The factorial of a positive integer is the product of that integer, one less than that integer, one less than that, etc all the way down to 1.

The notation for factorial is an exclamation point following the positive integer, e.g.

10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 725760.

As you can see, if you know the factorial of a particular positive integer, computing the factorial for the following positive integer simply requires multiplying what you know by that next value. Going the other way, if you *don't* know the factorial of a positive integer, you can simplify the solution of the product of the positive integer and the factorial of the next *lowest* positive integer.

(If you don't know the factorial of the next lowest positive integer, you can simply further to say that it is nothing more than the product of that next lowest positive integer and the factorial value of the next lowest value below that.)

Eventually, the question gets down to "what is the factorial value of 1? The answer is 1. Therefore, going back up the chain, the factorial value of 2, 2! = 2 * 1! = 2 * 1 = 2. And 3! = 3 * 2! = 3 * 2 = 6. 4! = 4 * 3! = 4 * 6 = 24, etc etc.

Okay: for this lab, you are to write a recursive function which computes what we'll call the "add factorial," i.e. *adding* up values, rather than multiplying:

If we let the hashtag stand for this function the way the exclamation point stands for factorial,

1# = 1

2# = 2 + 1! = 2 + 1 = 3

3# = 3 + 2# = 3 + 3 = 6

4# = 4 + 3# = 4 + 6 = 10

and so on.

The code you must write is *very* short but *very* powerful!

Write your main to prompt the user for various values for which to compute (and report!) the "add factorial." Entry of a negative value signals the program should stop.

Explanation / Answer

//Assuming for zero the program will stop
#include <iostream>
using namespace std;
int addfact(int n)
{
    if(n==1)
        return 1;
    return n + addfact(n-1);
}
int main()
{
    int n;
    while(1)
    {
        cout << "Please enter a number:";
        cin >>n;
        if(n>0)
        {
            cout<<addfact(n)<<' ';
        }
        else
        {
            cout << "Stopping....bye";
            break;
        }
    }
    return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote