Use of loop, l earn to organize code within a function, Learn to pass data to an
ID: 3685246 • Letter: U
Question
Use of loop, learn to organize code within a function, Learn to pass data to and return Boolean data from function
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.Title, Prompts, Output, Labels:
Program will write output to the file and to the standard output.
After closing the file, the program writes to the standard output:
a. on a line by itself :
b. a list of primes
Prime numbers are written to PrimeList.txt
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.
Explanation / Answer
Below are the two program written in C++ to achive the requested task:
#include <iostream>
using namespace std;
bool isPrime (int num);
int main ()
{
int num=0;
cout << "Enter a number to check if it is prime: "; //Enter a number to check whether it's prime or not
cin >> num;
if (isPrime(num)==true)
cout << num << " is prime.";
else
cout << num << " is NOT prime.";
return 0;
}
bool isPrime(int input)
{
if(input<1)
return false;
else if (input == 1||input ==2 ||input==3)
{
return true;
}
else
{
for(int i=2; i<input; i++)
{
if(input%i==0)
return false;
}
return true;
}
}
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main()
{
int num=0;
int i;
bool prime;
ofstream outFile;
outFile.open("PrimeList.txt"); //Prime No.s will be written to PrimeList.txt
while (num == 0 )
{
cin >> num;
}
for(i=2;i<num;i++)
if(isPrime(i))
outFile << i << " ";
cout << "Prime numbers written to PrimeList.txt. ";
outFile.close();
return 0;
}
bool isPrime(int n)
{
int i;
for(i=2;i<n-1;i++)
if(n%i==0)
return false;
return true;
}
Please comment if you face any issue in understanding anything on this C++ code. Happy to help :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.