Use the function definition to write a function that returns a boolean value tha
ID: 3673380 • Letter: U
Question
Use the function definition
to write a function that returns a boolean value that says if the user’s number is prime. In int main(), ask the user to enter a value. We will then write a while or for loop that will check if each value between 1 and the number the user entered is prime and output the result of each of those checks. Use our primeCheck function to check if numbers are prime rather than putting the algorithm inside int main()directly. This will help keep int main() nice and clean.
Sample Output
Explanation / Answer
#include<iostream>
#include<conio.h>
using namespace std;
bool primeCheck(int num);
int main()
{
int num;
cout<<"To print all prime numbers between 1 to N ";
cout<<"Enter value of N ";
cin>>num;
primeCheck(num);
return 0;
}
bool primeCheck(int num)
{
int i, isPrime, n;
for(n = 1; n <= num; n++){
isPrime = 0;
for(i=2;i<=n/2;i++){
if(n%i==0){
isPrime = 1;
break;
}
}
if(isPrime==0 && n!= 1)
cout<<n<<": is Prime";
else
cout<<n<<": not prime";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.