This is a C++ Program to Check if a Number is Prime.
The program checks if a number is prime. A prime number has only two factors – 1 and the number itself.
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.
Here is the source code of C++ Program to Check if a Number is Prime. The program output is shown below.
using namespace std;
int main ()
{
int num, i, count = 0;
cout << "Enter the number to be checked : ";
cin >> num;
if (num == 0)
{
cout << "\n" << num << " is not prime";
exit(1);
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
cout << "\n" << num << " is not prime.";
else
cout << "\n" << num << " is prime.";
return 0;
}
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.
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.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Apply for C++ Internship
- Buy C++ Books
- Buy Computer Science Books
- Practice Programming MCQs