Sunday 14 April 2019

for loop never ends in c

I'm trying to write a c program that prints a grid for each year. I have a for loop that iterates prints the grid for each year for how many years you choose in the argument.
The for loop prints the grid for an endless number of years exceeding the boundary put on it for some reason.
Here's the code:



    int main(int argc, char *argv[]) {
if (argc != 3) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */

printf("usage: %s filename", argv[0]);
} else {
int year = atoi(argv[1]);
double gridA[11][11];
double gridB[11][11];
int in;
int n;
printf("%d\n",year);
FILE *file = fopen(argv[2], "r");
for (int i = 0; i < 12; i++) {

fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3],
&gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7],
&gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]);
}
fclose(file);
for(n = 0; n < year; n++) {
printf("Year %d: \n", n);
if (n == 0) {
for (int i = 0; i < 12; i++) {

for (int j = 0; j < 12; j++) {
if (j == 11) {
printf("%.1lf\n", gridA[i][j]);
} else {
printf("%.1lf ", gridA[i][j]);
}
}
}
} else if (n % 2) {
in = nextDependency(gridA, gridB);

for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if (j == 11) {
printf("%.1lf\n", gridB[i][j]);
} else {
printf("%.1lf ", gridB[i][j]);
}
}
}
} else {

in = nextDependency(gridB, gridA);
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if (j == 11) {
printf("%.1lf\n", gridA[i][j]);
} else {
printf("%.1lf ", gridA[i][j]);
}
}
}

}
}
}
exit(0);
}


The for loop that never ends is this one:



for(n = 0; n < year; n++) {

printf("Year %d: \n", n); ...


Through attempting to debug I found that the loop is finite when before this code:



FILE *file = fopen(argv[2], "r");
for (int i = 0; i < 12; i++) {
fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3],
&gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7],

&gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]);
}


But when put after that code it loops infinitely, this is a bug I cannot figure out why it is happening? Does anyone have any idea how I could fix this?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...