Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c function not returning result

Tags:

c

function

return

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;
}
like image 517
user1895961 Avatar asked Jan 30 '26 18:01

user1895961


2 Answers

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.

like image 87
Michael Avatar answered Feb 02 '26 10:02

Michael


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.

like image 23
simonc Avatar answered Feb 02 '26 09:02

simonc