on Leave a Comment

C++ Program to Check Whether a Number is Prime or Not

In this C++ program, we check whether a number is prime or not. This program uses for loop, if-else statement and break statement. First of all, we need to know what is prime number.

Prime number: A number which is only divided 1 and itself is called prime number. A prime number cannot be divided by any other number except 1 and itself.

C++ Program to Check Whether a Number is Prime or Not

/*C++ Program to Check Whether a Number is Prime or Not*/
#include<iostream>
using namespace std;
int main()
{
    int a,i;
    cout<<endl<<"Enter a number : ";
    cin>>a;
    int flag=0;
    for(i=2;i<=a/2;i++)
    {
        if(a%i==0)
        {
            flag++;
            break;
        }
    }
    if(flag==1)
        cout<<endl<<a<<" is not a prime number";
    else
        cout<<endl<<a<<" is prime number";
    return 0;
}

OUTPUT:

Enter a number : 9

9 is not a prime number

In this program, first we read a number from keyboard using cin>>a; statement. After reading number, for loop is used to find whether a number is prime or not. 

Inside the for loop, variable i is incremented from 2 to a/2 (a is number to check whether prime or not) and if a is completely divided by i between any number from 2 to a/2, then flag (variable) is incremented and break statement causes the loop to terminate.

Outside the for loop, if-else statement is used to check the status to variable flag. If flag is 1, the number is not prime number and if flag is 0, number is prime number.     

C++ Program to Check Whether a Number is Prime or Not Using Function

/*C++ Program to Check Whether a Number is Prime or Not Using Function*/
#include<iostream>
using namespace std;
void checkprime(int x);
int main()
{
    int a,i;
    cout<<endl<<"Enter a number : ";
    cin>>a;
    checkprime(a);
    return 0;
}
void checkprime(int x)
{
    int i,flag=0;
    for(i=2;i<=x/2;i++)
    {
        if(x%i==0)
        {
            flag++;
            break;
        }
    }
    if(flag==1)
        cout<<endl<<x<<" is not a prime number";
    else
        cout<<endl<<x<<" is prime number";
}

OUTPUT:

Enter a number : 11

11 is prime number

0 comments:

Post a Comment