0

Im trying to do a exercise in one of my books and it wants me to use a function to get the factorial of a number entered by the user. Ive tried several different ways and they either get me numbers that make no sense or say if I entered 5, I would just get 25(which is what the code below does). Any help in the right direction would be great, thanks.

#include <iostream>
using namespace std;

int factorial(int n);

int main () {
        
        int n;
        
        cout << "Enter a number then press ENTER: ";
        cin >> n;
        
        cout << factorial(n) << " ";
        
        cin.get();
    return 0;
}

int factorial(int n) { 
        for (int i = n; i >= 1; i--) {
                return n = n * i;
        }
}
2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by element432
0

You're returning on the first iteration, so the result of factorial(5) is essentially 5 * 5 . A correction would initialize i to n - 1 , and only return n after the loop:

int factorial(int n)
{
    for (int i = n - 1; i >= 1; i--)
        n = n * i;

    return n;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.