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;
}
Your loop condition is
n >= 0, which means thatreswill be multipled by 0 before the function returns. Thus the result will always be 0.