103k views
2 votes
Write a function name isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Demonstrate the function in a complete program that reads in an integer that is less than 3001 stores a list of all the prime numbers from 2 through that number in a file named "PrimeList.txt" and to the standard output. Screenshot: Title, Prompts, Output, Labels: Program will write output to the file and to the standard output.1. A program writes the following text to the standard output(Can bee seen in the top of the screen shot): CMSC 140 CRN Project 5: Prime Numbers2. After closing the file, the program writes to the standard output:a. on a line by itself : Prime numbers are written to PrimeList.txtb. a list of primes Input Validation If the value read in exceeds 3000, the program writes on a line by itself in standard output: Your input integer should be less than 3001. Try again.

User Omer Raviv
by
7.4k points

1 Answer

2 votes

Answer:

Program is given in C++, appropriate comments used

Step-by-step explanation:

#include<iostream>

int isPrime(int n);

int main() //main function

{

int n, numPrime = 0;

FILE *fptr;

//create a empty file named "PrimeList.txt" at location where your program file is

fptr=(fopen("PrimeList.txt","w")); //open file in read mode

if(fptr==NULL) //if file does not exist exit the program

{

printf("File does not exist \\");

exit(1);

}

for(n = 2; n<3001; n++)

{

numPrime = isPrime(n);

if(numPrime)

{

printf("%d is prime \\",n);

fprintf(fptr,"%d \\",n);

}

}

fclose(fptr);

return 0;

}

int isPrime(int n) //function to check prime number between 2-3001

{

int flag = 0, i;

for(i=2;i<=n/2;++i)

{

if(n%i==0)

{

flag=1;

break;

}

}

if (flag==0)

return 1;

else

return 0;

}

User Sedrik
by
7.2k points