In this Program, you’ll learn how to Check Prime Number By Creating a Function or check prime numbers creating function.
To nicely understand this example to check prime numbers creating
- for Loop
- break and continue Statement
- if, if…else and Nested if…else
- Functions
- Types of User-defined Functions
Program to Check weather number is Prime or Not
#include <iostream>
using namespace std;
int checkPrimeNumber(int);
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
if(checkPrimeNumber(n) == 0)
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
}
int checkPrimeNumber(int n)
{
bool flag = false;
for(int i = 2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = true;
break;
}
}
return flag;
}
Output
Enter a positive integer: 23
23 is a prime number.
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.
Finally, the appropriate message is printed from the main()
function
Ask your questions and clarify your/others doubts on Program to check prime numbers creating the function by commenting. Documentation
Related Programs