C++ Program to check number is prime or not using the function


In this Program, You will learn how to check number is prime or not using the function in C++.


List of prime numbers => 2, 3, 5, 7, 11, 13, 17, 19

Example: How to check number is prime or not using the function in C++.

#include<iostream>
using namespace std;

int prime(int n) {

    int i, p = 1;

    for (i = 2; i < n; i++) {
        if (n % i == 0) {
            return p = 0;
            break;
        }
    }
    return p;
}

int main() {

    int n, c;

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

    c = prime(n);
    if (c == 1) {
        cout << "Number is prime:" << n;
    } else {
        cout << "Number is not prime:" << n;
    }

    return 0;
}

Output:

Enter a number:13
Number is prime:13