Search code examples
c++recursionfactorial

Factorial Recursive


I'm trying to write an algorithm to calculate the factorial of a number using recursive function.

This is my code :

#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
int factorial(int n) {
    cin >> n;
    if (n == 1)
        return 1;
    return n*factorial(n - 1);
}
int main() {
    int n = 0;
    cout<<"Enter a number:";
    cout << factorial(n);
    return 0;
}

It does nothing and I don't know why, it only lets me to give the number, but it's not calculating.


Solution

  • Inside the factorial function you are waiting for another input which is not needed. Remove this cin >> n; from inside the factorial method.

    Some other points which are not asked in the question:

    • Factorials grow very fast and by using int you will quickly get an overflow. You may consider to use 64 bit long long instead.
    • conio.h is not standard and should be avoided.
    • Calling using namespace std in global scope is very bad.