C++ Program to check a number is prime or not


In this program, You will learn how to check a number is prime or not in C++.


Some list of prime numbers is 2, 3, 5, 7, 11, 13

Example: How to check a number is prime or not in C++.

#include<iostream>
using namespace std;

int main() {

    int n, p = 1, i;

    cout << "Enter a number:";
    cin>>n;

    if (n == 1) {
        cout << "Number is not prime:" << n;
    } else {
        for (i = 2; i < n; i++) {
            if (n % i == 0) {
                p = 0;
                break;
            }
        }
        if (p == 1) {
            cout << "Number is prime:" << n;
        } else {
            cout << "Number is not prime:" << n;
        }
    }

    return 0;
}

Output:

Enter a number:13
Number is prime:13