This looks like a scoping problem. (Experienced programmers develop an instinct for such things.)
#include <stdio.h> int j; int fact( int n) { int value = 1; for ( j=1; j<=n; j++ ) value *= j; return value; } int main ( void ) { for ( j=1; j<7; j++ ) printf("factorial of %d is %d\n", j, fact(j) ); system("pause") ; return 0 ; }
Comments: The global variable j
is used as a loop control
variable in two loops that are sometimes both active. This can only lead to
problems.
The first time main
's loop executes, j
is set to
1. But then, just before fact
's loop exits, the same j
is set to 2. So the program writes out:
factorial of 2 is 1
The problem can be fixed by declaring a local variable for each loop. The problem in this example is obvious (I hope). But this is a frequent mistake in student programs. In a longer program, this problem is harder to find.