Home > Software engineering >  Is there any way to get rid of the "*" in the last digit of factorial of integers in C p
Is there any way to get rid of the "*" in the last digit of factorial of integers in C p

Time:10-15

The output of my code is:

5! = 1 * 2 * 3 * 4 * 5 * = 120

How can I remove the last * to have this output:

5! = 1 * 2 * 3 * 4 * 5 = 120 
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
            
    int n, count, factorial = 1;
    cout << "Enter a positive integer: ";
    cin >> n;
    cout << n << "! = ";
    
    if (n < 0){
        cout << "Error! Factorial of a negative number doesn't exist.";
        }
    else{
        while(count < n){
        count  ;
        factorial = factorial * count ;
        cout << count << " * ";  
        }
            cout << " = " << factorial;
    }
}

CodePudding user response:

Yes add an if that checks if you're not on your last number. (Also don't use using namespace std, Why is "using namespace std;" considered bad practice?)

#include <iostream>

int main(int argc, char** argv)
{

    int n = 0;
    int count = 0;
    int  factorial = 1;

    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    std::cout << n << "! = ";

    if (n < 0)
    {
        std::cout << "Error! Factorial of a negative number doesn't exist.";
    }
    else
    {
        while (count < n)
        {
            count  ;
            factorial = factorial * count;
            std::cout << count;

            // only show * if not on last number
            if (n != count) std::cout << " * ";
        }
        std::cout << " = " << factorial;
    }
}

CodePudding user response:

Your code, prettied up a little bit:

    else {
        while (count < n) {
            count  ;
            factorial  = count ;
            cout << count << " * ";  
        }
            
        cout << " = " << factorial;
    }

Now, let's put that " * " separator into a variable.

    else {
        string sep = " * ";

        while (count < n) {
            count  ;
            factorial *= count ;
            cout << count << sep;  
        }
            
        cout << " = " << factorial;
    }

Still the same result, but let's try this:

    else {
        string sep = " * ";

        while (count < n) {
            count  ;
            factorial *= count ;
            cout << sep << count;  
        }
            
        cout << " = " << factorial;
    }

Now we get the extra " * " in front of the first number. It'd work a lot better if sep were "" on the first iteration, and then we changed it to " * " on every other iteration.

    else {
        string sep = "";

        while (count < n) {
            count  ;
            factorial *= count ;
            cout << sep << count;  
            sep = " * ";
        }
            
        cout << " = " << factorial;
    }
  •  Tags:  
  • c
  • Related