[SOLVED] Program to print Factorial of a number in c++

Issue

Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120

Problem: I am able to print the result,but not able to print like this :

let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;

My Code:

# include <bits/stdc++.h>

using namespace std;


int Factorial (int N)
{
    int i = 0;int fact = 1;

    while (i < N && N > 0) // Time Complexity O(N)
    {
        fact *=  ++i;
    }

    return fact;
}

int main()
  {
    int n;cin >> n;
    
    cout << Factorial(n) << endl;
    return 0;
  }

Solution

I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;

That’s indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.

This should only be an idea this is far away from being a good example but it should do the job.

int main()
  {
    int n;cin >> n;
    
    std::cout << "Factorial of " << n << " = ";
    for (int i =1; i<=n; i++)
    {
        if(i != n)
            std::cout << n << " * ";
        else
            std::cout << n << " = ";
    }

    cout << Factorial(n) << endl;
    return 0;
  }

Better approach using std::string and std::stringstream

#include <string>
#include <sstream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    stringstream sStr;
    sStr << "Factorial of " << n << " = ";
    
    for (int i = 1; i <= n; i++)
    {
        if (i != n)
            sStr << i << " * ";
        else
            sStr << i << " = ";
    }
    sStr << Factorial(n) << endl;
    cout << sStr.str();
    return 0;
}

Answered By – AidenDean

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.