Easy Tutorial
❮ Cpp Examples Quotient Remainder Cpp Namespaces ❯

C++ Example - Check Prime Number

C++ Examples

A prime number (or prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. There are infinitely many prime numbers.

Example

#include <iostream>
using namespace std;

int main()
{
  int n, i;
  bool isPrime = true;

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

  for(i = 2; i <= n / 2; ++i)
  {
      if(n % i == 0)
      {
          isPrime = false;
          break;
      }
  }
  if (isPrime)
      cout << "Is a prime number";
  else
      cout << "Is not a prime number";

  return 0;
}

The above program outputs the following result:

Enter a positive integer: 29
Is a prime number

C++ Examples

❮ Cpp Examples Quotient Remainder Cpp Namespaces ❯