Check a given number is prime or not in C++ language

 

In this article, you’ll learn how to check a given number is prime or not in C++ language without giving input from the keyboard or giving input from the keyboard.

Q: what is the prime number

Ans: A natural number which only divided by itself and 1 is called a prime number and you also say that a prime number is a natural number which is greater than 1 and cannot be formed by multiplying two natural number.

  • 1 is not a prime number.
  • 2 is the smallest prime number and only even prime number.
  • Example of prime number 2,3,5,7,11,13 etc.

To check a given number is prime or not we generally use the following steps:

  • Let the given number be x.
  • Then we create a loop for checking the given number is prime or not.
  • Loop i=2 to x, we start the loop at 2 and check up to the given number . Here i is a variable and its initial value is 2, check up to i=x.
  • If (x % i==0) is false then the given number is prime otherwise it is not prime.

Loop is terminated two times:

  • First time, when the condition is true, terminated from the loop and with the help break keyword print on the screen number is not prime.
  • Second time, when the condition is false ( it means when the loop is fully executed) and print on the screen number is prime
  • If (i==x) is true then the number is prime
  • Else
  • Number is not prime.

 

Example 1: write a program in C++ language to check whether a number is prime or not, without input from keyboard

#include<iostream>

using namespace std;

int main()

{

int x=10,i;

for(i=2;i<x;i++)

if(x%i==0)

break;

if(i==x)

cout<<x<<” is a prime number”;

else

cout<<x<<” is  not a prime number”;

 return 0;

}

 

The Output of this program:

10 is a prime number

 

Example 2: write a program in C++ language to check whether a number is prime or not,  input is given from the keyboard.

 

Solution:

#include <stdio.h>

#include <conio.h>

int main()

{

  int x,i;

  printf(“Enter an integer number: “);

  scanf(“%d”,&x);

  for(i=2;i<=x;i++)

  if(x%i==0)

  break;

  if (i==x)

  printf(“%d is a prime number”,x);

  else

  printf(“%d is not a prime number”,x);

  getch();

}

 

The Output of this program:

Enter an integer number: 27

27 is not a prime number

 

How to reverse  a number in C++

Leave a Reply

Your email address will not be published. Required fields are marked *

itetrade.com