Factorial Recursion

I am doing an assignment displaying a table of factorials from 0 to 20 using recursion. Everything works fine, but I can not figure out how to display the correct value for 0. I have tried several modifications within the function, but feel there must be some bit of logic I am misunderstanding. Any nudge in the right direction would be appreciated. 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
long factorial(int n);
int main(int argc, char** argv) 
{    
    const int max=20;
    int n=1;
    cout<<setw(5)<<"Integer"<<setw(22)<<"Factorial\n";
    for(n=0;n<=max;n++)
    {
        factorial(n);
        cout<<setw(3)<<n<<setw(25)<<factorial(n)<<endl;
    }
    return 0;
}
long factorial(int n)
{
    if(n==0)
    {
        return 1;
    }
    {
        return n*factorial(n-1);
    }
}
What is the correct value for 0! ?
https://en.wikipedia.org/wiki/Factorial


What is the purpose of line 9?


PS. Could one print all those values without any loop?
I see. So I should think of 0! basically like an exponent. Thank you for that. I meant to edit line 9 out when I was trying to figure out how to print the table. I really can't think of another way to print all of the values that wouldn't over-complicate the code.
Ok. Can you trace what I do here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>

using std::setw;
long factorial(int);

int main() 
{    
    const int max=20;
    std::cout << setw(5) << "Integer\n";
    factorial(max);
    return 0;
}

long factorial(int n)
{
    std::cout << 'B' << setw(3) << n << '\n';
    const long fact = (n) ? n * factorial( n-1 ) : 1;
    std::cout << 'A' << setw(3) << n << '\n';
    return fact;
}
Topic archived. No new replies allowed.