Factorial problem


I am trying to create a program where you input a number, and it returns the factorial of it. Here is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

int factorial(int);
int n;

int main(void){

    using namespace std;
    cout << "Enter your factorial" << endl;
    cin >> n;
    cout << factorial(n) << endl;
}

int factorial(int n){
    int temp;
    temp = n;

    if ( n == 1 ){
        return 1;
    }
    else if ( n > 1 ){
    return factorial(temp) * factorial(temp-1);
    }
    else if ( n > 25 ){ std::cout << "Input too large, try a number less than 25" << std::endl;
    }
    else ( n < 1 );{ std::cout << "No negative numbers" << std::endl;
    }
}

All advice is welcome!
Ah well I got it to run, but im still new and could use some help with my syntax and C++ in general.
[code]
#include <iostream>

int factorial(int);
int n;

int main(void){

using namespace std;
cout << "Enter your factorial" << endl;
cin >> n;
cout << factorial(n) << endl;
}

int factorial(int n){
if ( n == 1 ){
return 1;
}
else if ( n > 1 ){
return n * factorial(n-1);
}
else if ( n > 25 ){ std::cout << "Input too large, try a number less than 25" << std::endl;
}
else ( n < 1 );{ std::cout << "No negative numbers" << std::endl;
}
}

[code/]
You don't need the variable temp

This is the value of the factorial of n: n! = n * ( n-1 )!
Line 22 says n! = n! * (n-1)

[EDIT] You fixed this on your second post

The if condition of line 24 will never be matched because if the input is eg 26 it will match if ( n > 1 ) and the control flow will reach the return on line 24

For conditions in lines 18, 21 and 26 you should use 0 instead of 1

The function is missing some returns ( you must always return a value from a non-void function )
Last edited on
Topic archived. No new replies allowed.