The below code perfectly calculates the factorial of a number.
#include <stdio.h>
long int f_fact(int i);
int main() {
int a;
long int factorial;
printf("Please enter a number\n");
scanf("%d", &a);
factorial = f_fact(a);
printf("The factorial is %ld\n", factorial);
return 0;
}
long int f_fact(int i) {
int j;
long int factorial = 1;
for (j = 2; j <= i; ++j) {
factorial = factorial * j;
}
return (factorial);
}
However, this other code doesn't. The only difference is having this for (j = 2; j <= i; ++i)
instead of this for (j = 2; j <= i; ++j)
.
#include <stdio.h>
long int f_fact(int i);
int main() {
int a;
long int factorial;
printf("Please enter a number\n");
scanf("%d", &a);
factorial = f_fact(a);
printf("The factorial is %ld\n", factorial);
return 0;
}
long int f_fact(int i) {
int j;
long int factorial = 1;
for (j = 2; j <= i; ++i) {
factorial = factorial * j;
}
return (factorial);
}
My question is how can I best spot these little mistakes in the code? Right now, I have -Wall
and -Wextra
activated, but even with those I am getting: Errors: 0
and Warnings: 0
which makes it a bit harder to spot the issue. Any recommendations to better work my way through bugs? Thank you!