Write a C++ Program to Check Prime Number By Creating a Function

In this tutorial, we will learn how to write a C++ program to check whether a given number is prime or not by creating a function.

A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, 13, 17, 19, and 23 are prime numbers.

To check if a given number is prime or not, we can create a function that takes the number as input and returns true if the number is prime and false otherwise.

Let’s write the C++ program to check whether a given number is prime or not by creating a function:

#include <iostream>
using namespace std;

bool isPrime(int number) {
    if (number <= 1) {
        return false;
    }
    for (int i = 2; i <= number / 2; ++i) {
        if (number %% i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int number;
    cout << "Enter a positive integer: ";
    cin >> number;
    if (isPrime(number)) {
        cout << number << " is a prime number" << endl;
    } else {
        cout << number << " is not a prime number" << endl;
    }
    return 0;
}

In this program, we first create a function called isPrime that takes an integer number as input and returns true if the number is prime and false otherwise.

Inside the isPrime function, we first check if the number is less than or equal to 1.

If it is, we immediately return false because 1 and all numbers less than 1 are not prime.

Next, we loop from 2 to number / 2 and check if number is divisible by any number between 2 and number / 2. If it is, we immediately return false because number is not prime.

Finally, if none of the numbers between 2 and number / 2 divide number exactly, we return true because number is prime.

In the main function, we first ask the user to enter a positive integer.

We then call the isPrime function with the input number and print a message indicating whether the number is prime or not.

That’s it! We have successfully written a C++ program to check whether a given number is prime or not by creating a function.