I am new to C programming (although I have experience with Java). After reading some tutorials, I decided to start solving coding challenges on Coderbyte.
The first challenge I tried was this one:
Challenge
Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer.
Sample Test Cases
Input: 4
Output: 24Input: 8
Output: 40320
My solution:
#include <stdio.h>
void FirstFactorial(int num[]) {
int i = num -1;
for(i ; i > 0; i--) {
num = num * i;
printf("%d",i);
}
printf("\t %d", num);
}
int main(void) {
// disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);
// keep this function call here
FirstFactorial(gets(stdin));
return 0;
}
Value of the input parameter: 8
Error message:
main.c: In function 'FirstFactorial':
main.c:5:11: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
int i = num -1;
^~~
main.c:8:15: error: invalid operands to binary * (have 'int *' and 'int')
num = num * i;
^
main.c: In function 'main':
main.c:23:18: warning: passing argument 1 of 'FirstFactorial' makes pointer from integer without a cast [-Wint-conversion]
FirstFactorial(8);
^
main.c:3:6: note: expected 'int *' but argument is of type 'int'
void FirstFactorial(int num[]) {
^~~~~~~~~~~~~~
exit status 1
So there seems to be a few problems, and I have a few questions:
I've never heard of
gets(stdin)
. I looked upgets()
, and the glibc documentation says the function returns achar*
. How can I pass it to a function that takes anint
?It looks like
int i = num -1;
is initializing
i
as 4 and not 7. Why?The for loop seems to be decrementing
i
correctly (i
= 7, 6, 5, 4, 3, 2, 1). But this statement:num = num * i;
is generating an error. What is wrong with it? It looks like a normal multiplication.