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

To understand this example, you should have the knowledge of the following C++ programming topics:


Example: Check Prime Number

#include <iostream>
using namespace std;

bool check_prime(int);

int main() {

  int n;

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

  if (check_prime(n))
    cout << n << " is a prime number.";
  else
    cout << n << " is not a prime number.";

  return 0;
}

bool check_prime(int n) {
  bool is_prime = true;

  // 0 and 1 are not prime numbers
  if (n == 0 || n == 1) {
    is_prime = false;
  }

  for (int i = 2; i <= n / 2; ++i) {
    if (n % i == 0) {
      is_prime = false;
      break;
    }
  }

  return is_prime;
}

Output

Enter a positive  integer: 23
23 is a prime number.

In this example, the number entered by the user is passed to the check_prime() function.

This function returns true if the number passed to the function is a prime number, and returns false if the number passed is not a prime number.

Finally, the appropriate message is printed from the main() function.

To learn how the check_print() function works in detail, visit C++ Check Prime Example.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges