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;
        }
}

Recommended Answers

All 2 Replies

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;
}

Ok thanks for the help, I got it too work.

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.