Program to check whether the number is prime or not

0 Suresh Chand March 28, 2021

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

Prime Numbers are those numbers which is divisible by 1 and itself. Eg: 2,3,5,7,11 etc.

We will check the prime number by simply dividing all the number below that number. Suppose, If we have to check the 5 then we will divide 5 by 2,3 and 4. If the anyone gives remainder 0 then that is not a prime.

Let’s look and example to make clear concepts

#include<iostream>
using namespace std;

int main()
{
    int num, i, flag = 0;

    cout << "Enter a Number: ";
    cin >> num;

    for( i = 2; i < num; i++)
    {
        if( num % i == 0)
        {
            flag = 1;
            break;
        }
    }
    if( flag == 0 )
        cout << "\nIt is a Prime Number" << endl;
    else
        cout << "\nIt is not a Prime Number" << endl;
    
    return 0;
}

The output of above program is

Enter a number : 5
It is a Prime Number

Enter a number : 6
It is not a Prime Number

Let’s understand how program working:

  • Step 1: First we will initialize variables num, i and flag = 1
  • Step 2: We will read the number
  • Step 3: We will loop from 2 to that number. If any number gives remainder while dividing then we will set flag = 1
  • Step 4: After loop end, We will change whether flag value is o or 1. If flag value has initial value then number is prime else number is not prime.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

!

Ads

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System