C++ Program to Check Prime Number By Creating a Function


A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself.

Some of the first prime numbers are −

2, 3, 5, 7, 11, 13 ,17

A program to check if a number is prime or not using a function is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
void isPrime(int n) {
   int i, flag = 0;
   for(i=2; i<=n/2; ++i) {
      if(n%i==0) {
         flag=1;
         break;
      }
   }
   if (flag==0)
   cout<<n<<" is a prime number"<<endl;
   else
   cout<<n<<" is not a prime number"<<endl;
}
int main() {
   isPrime(17);
   isPrime(20);
   return 0;
}

Output

17 is a prime number
20 is not a prime number

The function isPrime() is used to find out if a number is prime or not. There is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop as shown below −

for(i=2; i<=n/2; ++i) {
   if(n%i==0) {
      flag=1;
      break;
   }
}

If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.

if (flag==0)
cout<<n<<" is a prime number";
else
cout<<n<<" is not a prime number";

The function isPrime() is called from the main() function for the values 17 and 20. This is shown as follows.

isPrime(17);
isPrime(20);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements