Courses

# Program to check prime number using Functions

0 Suresh Chand March 28, 2021

In this example, We will check whether number is prime or not.

To understand this example, You must have knowledge in following topics

Lets look a code

``````#include <iostream>
using namespace std;

int main() {
int n;

cout << "Enter a positive  integer: ";
cin >> n;

cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}

bool isPrime = true;

// Since, 0 and 1 are not prime
if (n == 0 || n == 1) {
isPrime = false;
}
else {
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
return isPrime;
}``````

The output of above code is

``````Enter a positive  integer: 12
12 is not a prime number.

Enter a positive  integer: 5
5 is a prime number.``````

In this example, We have create one function isPrimeNumber() which return Boolean value.

It accepts one number and return Boolean(true or false) value. It return true if number passed is prime number and false it number passed is not prime number.

To know the detail about the program to check prime number.

Please check that example for detail explanation to check the prime number using C++ programming language.

Subscribe
Notify of
Inline Feedbacks