user1895961
user1895961

Reputation: 1186

c function not returning result

I've very recently started to learn C, so I realize my question is very basic, but any help would be very much appreciated.

I'm trying to get the function fact to return the res value to main, but when I print out the result in main I just get 0. By inserting some print statements I can see that res is calculating correctly in the fact routine but the result is not returning correctly to main.

I'm sure I'm missing something very basic here.

Thanks

#include <stdio.h>

unsigned long fact (int n){
    unsigned long res = 1;

    while ( n >= 0 )
    {
        res *= n;
        n--;
    }

    return res;
}

int main (void){
    int n;
    unsigned long res;

    printf("Insert number:\n");
    scanf("%d", &n );

    res = fact (n);

    printf("The factorial number is %lu", res);

    return 0;
}

Upvotes: 2

Views: 238

Answers (2)

simonc
simonc

Reputation: 42195

You loop condition is wrong. The last run of while (n>=0) will have n=0. Multiplying res by this will reset it to 0.

You can fix this by changing your loop to while (n > 1)

For future reference, you could investigate problems like this using a debugger (e.g. GDB or visual studio express). Or by adding printf statements to your code to trace the flow and see how the value of res changed through the program.

Upvotes: 6

Michael
Michael

Reputation: 58507

Your loop condition is n >= 0, which means that res will be multipled by 0 before the function returns. Thus the result will always be 0.

Upvotes: 7

Related Questions