- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are −

2, 3, 5, 7, 11, 13 ,17

The program to check if a number is prime or not is as follows.

## Example

#include <iostream> using namespace std; int main() { int n=17, i, flag = 0; for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=1; break; } } if (flag==0) cout<<n<<" is a prime number"; else cout<<n<<" is not a prime number"; return 0; }

## Output

17 is a prime number

In the above program, there is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop.

for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=1; break; } }

If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.

if (flag==0) cout<<n<<" is a prime number"; else cout<<n<<" is not a prime number";

- Related Questions & Answers
- C Program to Check Whether a Number is Prime or not?
- Java Program to Check Whether a Number is Prime or Not
- Write a Golang program to check whether a given number is prime number or not
- C# Program to check if a number is prime or not
- How to check whether a number is prime or not using Python?
- C++ Program to Check Whether a Number is Palindrome or Not
- Program to check whether every rotation of a number is prime or not in Python
- Check whether N is a Dihedral Prime Number or not in Python
- Program to check whether a number is Proth number or not in C++
- Write a C# program to check if a number is prime or not
- Python program to check if a number is Prime or not
- PHP program to check if a number is prime or not
- Check whether the given number is Wagstaff prime or not in Python
- Bash program to check if the Number is a Prime or not
- Check if a number is Quartan Prime or not in C++