Checking if a Number is a Prime Number in C++

Exercise:

Write a C++ program to check if the number is a prime number or not.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main() 
{
    int num, Prime = 1;     
    // bool Prime = true
    cout << "Enter a positive integer: ";
    cin >> num;
    // since 0 and 1 are not prime numbers
    if (num = 0 || num == 1)
    {
        Prime = 0;
    }
    else 
    {
        for (int i = 2; i <= num / 2; ++i) 
        {
            if (num % i == 0)
            {
                Prime = 0;
                break;
             }
        }
    }
    if (Prime)
        cout << "it is a prime number";
    else
        cout << " is not a prime number";
    return 0;
}
Click Here to View the Output:
Enter a positive integer: 23
it is a prime number
Click Here to View the Explanation:
  • Some variables are declared in this program. num and Prime. The value of Prime is declared as 1.
  • The user is requested to enter a number.
  • The value of Prime can be changed to zero using an if statement and an OR operator.
  • It checks if the entered numbers are 0 or 1, the Prime value is changed to zero, the compiler jumps to the last step and prints out that the entered number is a prime number.
  • If Prime remains 1, the for loop is iterated. It checks if i perfectly divides num leaving 0 as remainder.
  • A range is given to enter the for loop, listing that it can only be entered if value of i is lesser than num/2 and/or equal to 2.
  • With every iteration, the value of i is increased by 1 through increment operators.
  • If the number is divided by i at any iteration, the Prime is reduced to zero and the for loop is exited.
  • The output is printed accordingly.
%d bloggers like this: