Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Input Question 7: Write a program to read an integer N (2 <= N <= 10000) from an

ID: 3709772 • Letter: I

Question

Input
Question 7: Write a program to read an integer N (2 <= N <= 10000) from an input file named “input7.txt” and then outputs
a. All numbers that are divisible by 3 to the output file named “output7A.txt” b. All primes from 2 to N to the output file named “output7B.txt” Requirements:
+ For each part a) and b), define a method called readDataFromFile() that takes into account the input filename as the parameter and returns the number N.
+ In part a), write a function called printNumbersToFile() that takes the output filename as the parameter and prints out all numbers which are divisible by 3 (0 excluded).
+ In part b), write a function called printPrimesToFile() that takes the output filename as the parameter and prints out all primes. Example:

File “input7.txt”
10
Output
File “output7A.txt”
3 6 9
File “output7B.txt”
2 3 5 7

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>

int main(){

FILE *fptr;
fptr = fopen("Input7.txt", "r");
FILE *filemod3;
filemod3 = fopen("Output7A.txt", "w");
FILE *fileprime;
fileprime = fopen("Output7B.txt", "w");
int i=0, j = 0, num1;

fscanf(fptr, "%d", &num1);
if ((num1 >= 2) && (num1 <= 10000)){
for (i=2;i<num1;i++){

if (i % 3 == 0){
fprintf(filemod3, "%d ",i );
}

for (j=2;j<i;j++) { /* check for nontrivial divisors */
if (i % j == 0) {
break; /* nontrivial divisor found -> not a prime */
}
}
if (j == i) { /* this means the cycle above run till end */
fprintf(fileprime, "%d ",i ); /* hence no nontrivial divisors, hence a prime */
}
}
}
else printf("Enter proper input in file Input7.txt");
fclose(fptr);
fclose(filemod3);
fclose(fileprime);
return 0;
}

/*************** OUTPUT OF PROGRAM ******************************

“Input7.txt”
10
Output
File “Output7A.txt”
3 6 9
File “Output7B.txt”
2 3 5 7

********************************************/