C++ Factorial, Prints the Equation, How to print Answer?

So I am doing C++ course, and Mosh made an answer with answer and not equation for the factorial exercise, how can I implement answer to in this program with only few changes?

// Online C++ compiler to run C++ program online
#include <iostream>

using namespace std;

int main() {
    int factorial;
    cout << "Number(Positive Please): ";
    cin >> factorial;

    if (factorial < 0) 
        cout << "Not Positive! ";
    
    if (factorial == 0) cout << 1;
    else {
        for (int i = factorial; i > 0; i--){
            cout << i;
            if (i == 1)
                cout << endl << "Done";
            else 
                cout << " * ";
        }
    }

    return 0;
}

Sorry for deleting the last three replies! I was trying(three times) to give you a fruitful solution.

I hope this solution would help you!

#include <iostream>

using namespace std;

int main() {
    int num;
    cout << "Number(Positive Please): ";
    cin >> num;

    if (num < 0) 
        cout << "Not Positive! ";
    
    if (num == 0) cout << 1;

    else { 
        int factorial = num;
        for (int i = factorial; i > 0; i--){
            if(i == 1)
                cout<< i;
            else{
                cout << i
                     << " * ";
                }
            }

        int finalOutput = 1;
        for (int i = 2; i <= num; ++i){
            finalOutput *= i;
         }

         if(finalOutput == 1)
         cout <<"*1 = "<< finalOutput<<endl;
         
         else { cout <<" = "<< finalOutput<<endl;}
         cout<< "Done";
    }
    return 0;
}
1 Like