C++ Program to Check Prime Number By Creating a Function
In this example, we will learn a program check whether a number entered by the user is prime or not by passing it to a user-defined function.
To understand this example, you should have the knowledge of the following C++ programming topics:
- C++ Functions
- C++ if, if...else and Nested if...else
- C++ For Loop
- C++ break and continue Statement
- C++ User-defined Functions
Example: Program to Check Prime Number By Creating a Function
# include <iostream>
using namespace std;
bool checkPrimeNumber(int);
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (checkPrimeNumber(n))
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}
bool checkPrimeNumber(int n) {
bool isPrime = true;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = false;
}
else {
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
return isPrime;
}
Output 1
Enter a positive integer: 23 23 is a prime number.
Working
In this example, the number entered by the user is passed to the checkPrimeNumber()
function.
This function returns true
if the number passed to the function is a prime number, and returns false
if the number passed is not a prime number.
The detailed logic of the checkPrimeNumber()
function is given in our C++ Prime Number tutorial. Finally, the appropriate message is printed from the main()
function
Next Example
We hope that this Example helped you develop better understanding of the concept of "Prime Number By Creating a Function" in C++.
Keep Learning : )
In the next Example, we will learn about C++ Check Whether a Number can be Expressed as Sum of Two Prime Numbers
.