beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C++ Program to Check whether an input number is Prime or not

By Chaitanya Singh | Filed Under: C++ Programs

A number which is only divisible by itself and 1 is known as prime number, for example: 5 is a prime number because it is only divisible by itself and 1.

This program takes the value of num (entered by user) and checks whether the num is prime number or not.

Example: Check whether number is prime number or not

To understand this program you should have the knowledge of for loop, if-else, break statement in C++.

#include <iostream>
using namespace std;
int main(){
   int num;
   bool flag = true;
   cout<<"Enter any number(should be positive integer): ";
   cin>>num;

   for(int i = 2; i <= num / 2; i++) {
      if(num % i == 0) {
         flag = false;
         break;
      }
   }
   if (flag==true)
      cout<<num<<" is a prime number";
   else
      cout<<num<<" is not a prime number";
   return 0;
}

Output:

Enter any number(should be positive integer): 149
149 is a prime number

You can also use while loop to solve this problem, just replace the following code in above program:

for(int i = 2; i <= num / 2; i++) {
   if(num % i == 0) {
      flag = false;
      break;
   }
}

with this code:

int i=2;
while(i<=num/2){
   if(num % i == 0)
   {
      flag = false;
      break;
   }
   i++;
}

Enjoyed this post? Try these related posts

  1. C++ Program to Display the Number Entered by User
  2. C++ Program for Binary Search
  3. C++ Program to add two numbers
  4. C++ Program to Convert Uppercase to Lowercase
  5. C++ Program to find the sum of n natural numbers
  6. C++ Program to Check Leap Year using function

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap