In the following code, my last statement in main function is return fact(n) does not work.

But if I substitute it with printf ("Factorial of %d = %d\n", n, fact(n)); it works

My question is if main function expects int as return value, why does the first option not work?

#include <cs50.h>
#include <stdio.h>

int fact (int n)


    if (n==0)
    return 1;

    if (n == 1)
    return 1;

    return n* fact(n-1);

int main(void)


    int n;
    printf ("Enter your number for whose factorial you want? \n");

    scanf ("%d", &n);

    return fact(n);


Hint for formatting code: after you paste it into question, select it and click {} icon in the format bar. (you can do the same when you edit the question).

The return value from main is not automatically displayed anywhere. You can see the result by typing echo $? immediately after the program finishes. echo $? displays the return value of the most recently executed command. This is covered in Week 2 notes.

We can see the exit code in terminal like this:

~/workspace/ $ ./exit
missing command-line argument
~/workspace/ $ echo $? 1

$? is a magic symbol for the previous program’s exit code, and echo is a command-line program that just prints out values


The value is actually returned to the main function ...but it is not printed in the terminal ..so ur second option prints it in the screen, so you'll know the returned valu:).vote if you understood ..happy coding


Your fact() function looks like it is correctly written. The problem lies in how you are calling it in/from main:

    return fact(n);

This line means "Take the value returned by fact(n), return that value to the operating system, and terminate main()." If you want to use the value returned by fact(n) and continue to execute the main program, you have to actually do something with it. You could assign it to an int var:

    int result = fact(n);

or print it:

    printf("%i factorial = %i\n", n, fact(n) );

or you could return it to the operating system and end the program as you did, or any number of other options.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .