In: Computer Science
Write a value returning function called isPrime. This function accepts integer number as parameter and checks whether it is prime or not. If the number is prime the function returns true. Otherwise, function returns false. A prime number is the number that can be divided by itself and 1 without any reminder, i.e. divisible by itself and 1 only.
DO THIS USING C++ LANGUAGE .WITH UPTO CHAPTERS 5 (LOOP).
Code:
#include<iostream>
using namespace std;
bool isPrime(int n) { //isPrime() function which accepts n value
for (int i=2;i<=n/2;i++) { //iterate loop from 2 to n/2
if (n%i==0) //check n is divisible with any value i if yes return false
return false; }
if (n>1)
return true; //if there is no factors for n and n>1 then return true
else
return false; //if n<=0 return false
}
int main() {
int number;
cout << "Enter a number: "; //asking user to
enter a number
cin >> number; //take number from user
if (isPrime(number)) //call isPrime() if result is true print prime else not prime
cout << number << " is a prime number." << endl;
else
cout << number << " is not a prime number." << endl;
return 0;
}
Code and Output Screenshots:
Note: if you have any queries please post a comment thanks a lot..always available to help you...