#include <stdio.h>
int main() {
int a,i,j;
FILE *fp,*fw;
fp=fopen("new.txt", "r");
fw=fopen("exam.txt", "w");
for (i=0; i<4; i ) {
int flag=0;
fscanf(fp,"%d",&a);
for(j=2;j<a;j )
{
if(a%j==0){
flag=1;
}
}
}
if(flag==0){
fprintf(fw,"%d number is prime \n",a);
}
else
{
fprintf(fw, "%d number is not prime \n",a);
}
fclose(fp);
fclose(fw);
}
ı want to print to file exam.txt whether the numbers in file new.txt are prime or not but when ı run the code it always writing 'number is not prime' .
CodePudding user response:
You are declaring flag inside the for loop. So it is not accessible outside the for loop. You need to declare it outside the for loop.
CodePudding user response:
A declaration, like int flag=0;
, only makes an identifier known (available for use) within a region of the source code. That region is called the scope of the identifier. Within int flag=0;
inside the compound statement formed by { … }
, its scope starts at the declaration and ends at the }
.
Your if(flag==0)
appears after that scope, so the identifier is not available for use at that point.
To make it available, move int flag=0;
to earlier in the program, possibly just before the for
statement.
The defined object also has a lifetime, which is the period of time during program execution that memory is reserved for it. Lifetimes are organized in classes called storage durations. An object defined inside a function without static
or extern
has automatic storage duration. For most objects with automatic storage duration, its lifetime begins when execution of its associated block starts and ends when execution of its associated block ends. If the object has a variable length array type, its lifetime starts when execution reaches its definition.