C++ Program to Check Prime Number

«
»

This is a C++ Program to Check if a Number is Prime.

Problem Description

The program checks if a number is prime. A prime number has only two factors – 1 and the number itself.

Problem Solution

1. The number to be checked is entered.
2. If it is divisible by any natural number from 2, then is it is not a prime number.
3. Else it is a prime number.
4. The result is printed.
5. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Check if a Number is Prime. The program output is shown below.

  1. using namespace std;
  2. int main ()
  3. {  
  4.     int num, i, count = 0;
  5.     cout << "Enter the number to be checked : ";
  6.     cin >> num;
  7.     if (num == 0)
  8.     {
  9.         cout << "\n" << num << " is not prime";
  10.         exit(1);
  11.     }
  12.     else   {
  13.             for(i=2; i < num; i++)
  14.                 if (num % i == 0)
  15.                     count++;
  16.     }
  17.     if (count > 1)
  18.  	    cout << "\n" << num << " is not prime.";
  19.     else
  20.         cout << "\n" << num << " is prime.";
  21.     return 0;
  22. }
Program Explanation

1. The user is asked to enter the number to be checked and stored in the variable ‘num’.
2. The variable ‘count’ is initialized as 0.
3. If num is 0, it is not a prime number.
4. The result is printed and program is exited.
5. Else, using a for loop starting from 2, num is checked if it is divisible by any natural number.
6. If it is divisible, count is incremented.
7. The loop is exited when the condition is not true.
8. If count is greater then 1, it is not a prime number, else it is a prime number.
9. The result is then printed.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter the number to be checked : 5
5 is prime.
 
Case 2 :
Enter the number to be checked : 0                                                                                         
0 is not prime.
 
Case 3 :
Enter the number to be checked : 28
28 is not prime.

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.