Introduction
Control Statement
- Check Whether the Number is Even or Odd in C++
- Program to check whether the number is prime or not
- Program to check vowel or constant
- Program to check the largest number among three numbers
- Program to the sum of natural numbers
- Program to check leap year
- Program to find factorial of the number
- Program to find reverse of the number
- Program to Check Armstrong Number
Function
- Program to find LCM
- Program to check prime number using Functions
- Program to convert Binary to Decimal Number
- Program to convert Decimal to Binary Number
- Program to convert Binary to Octal Number
- Program to convert Octal to Binary Number
- Program to find reverse of the sentence using Recursion
- Program to Shutdown and restart Computer
- Program to find the area of triangle
Array
Pointer
OOPS
No Examples found for this topic - CodeHelpPro
Program to check prime number using Functions
In this example, We will check whether number is prime or not.
To understand this example, You must have knowledge in following topics
Lets look a code
#include <iostream>
using namespace std;
bool isPrimeNumber(int);
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (isPrimeNumber(n))
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}
bool isPrimeNumber(int n) {
bool isPrime = true;
// Since, 0 and 1 are not prime
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;
}
The output of above code is
Enter a positive integer: 12
12 is not a prime number.
Enter a positive integer: 5
5 is a prime number.
In this example, We have create one function isPrimeNumber() which return Boolean value.
It accepts one number and return Boolean(true or false) value. It return true if number passed is prime number and false it number passed is not prime number.
To know the detail about the program to check prime number.
Please check that example for detail explanation to check the prime number using C++ programming language.
Subscribe
Login
0 Comments
Inline Feedbacks
View all comments