Google News
logo
C++ Program to Check Prime Number By Creating a Function
In the following example of C++ program that checks if a number is prime by creating a function :
Program :
#include <iostream>

using namespace std;

bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }

    for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            return false;
        }
    }

    return true;
}

int main() {
    int n;
    bool result;

    cout << "Enter a positive integer: ";
    cin >> n;

    result = isPrime(n);

    if (result) {
        cout << n << " is a prime number";
    } else {
        cout << n << " is not a prime number";
    }

    return 0;
}
Output :
Enter a positive integer: 31
31 is a prime number
* This program defines a function isPrime() that takes an integer argument and returns a boolean value indicating whether or not the number is prime.

* The function checks if the number is less than or equal to 1 (which is not prime), and then loops through all the integers from 2 to half of the number, checking if any of them divide evenly into the number. If one does, the number is not prime.

* In the main() function, the program prompts the user to enter a positive integer, calls the isPrime() function on that integer, and outputs the result.