One of my assignments is to write a factorial function. I have no clue how to start this program. HELP!!

This is my assignment..

Example Outputs
Enter the number: 5
The factorial of 5 is 120

Enter the number: 0
The factorial of 0 is 1

Enter the number: -8
Invalid Input


how do i do this?

Recommended Answers

All 3 Replies

5 factorial:

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

4! = 4 x 3 x 2 x 1 = 24

15! = 15 x 14 x 13 x 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 1307674368000

To get the other values ( for 0 and then for negative ), first check if the number is greater than 0, if it is, then do the factorial. If it isn't check if it is equal to zero, if so, " The factorial of 0 is 1 " otherwise "Invalid Input"

Good enough?

5 factorial:

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

4! = 4 x 3 x 2 x 1 = 24

15! = 15 x 14 x 13 x 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 1307674368000

To get the other values ( for 0 and then for negative ), first check if the number is greater than 0, if it is, then do the factorial. If it isn't check if it is equal to zero, if so, " The factorial of 0 is 1 " otherwise "Invalid Input"

Good enough?

so far I have

int factorial (int n);
//Returns factorial of n.
//The argument n should be nonnegative

{
    int product = 5;
    for (n > 0)
    {
        product = n!;
        n--;
    }

    return product;
}

written but i'm not sure where to go from here. it is still giving me an error

There's no operator for a factorial in C++, you need to perform the multiplications manually. You have the right idea though, now it's just a matter of details. Here are a couple of things to consider down the road:

  • This factorial function accepts a signed integer argument, which means n could be a negative value. A robust implementation would handle negative values sensibly.
  • Factorials are a great way to overflow your data type because they grow so quickly. An overflow check would be a fantastic idea in the case of an n that's too large for int.

>int product = 5;
Start the product at n rather than any hard value. Also, be sure to check for 0 as 0! is 1.

>for (n > 0)
Anything multiplied by 1 is itself, so you can stop the loop before n reaches 1.

>product = n!;
Obviously this should be product = product * n; . Otherwise a factorial function would be unnecessary. ;)

>n--;
product is set to n originally, so you need to decrement n before the multiplication step. As it is you'll start off with n * n rather than n * n - 1 .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.