In this tutorial you will learn about the C++ Program to Check Prime Number Using Function and its application with practical example.
C++ Program to Check Prime Number Using Function
In this tutorial, we will learn to create a C++ program that will Check Prime Number Using functions using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ programming.
- Conditional Statements in C++ programming.
- Arithmetic operations in C++ Programming.
Program to Check Prime Number Using Function:-
A prime number is a number that is only divisible by only one number or by itself only. In c++ programming, it is possible to take numerical input from the user and check if that number is Prime Number or not with the help of a very small amount of code.
In this program, we will take a number in the input from the user to check if it’s prime or not.
With the help of this program, we can Check Prime Number Using Function.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input number from the user. 3. Calculating the number is a prime number or not. 4. Printing the result. 5. End the program. |
Program to Check Prime Number Using Function:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <iostream> using namespace std; bool checkPrimeNumber(int); int main() { //declaring the variables for the program int n; //taking the input from the user cout << "Enter a positive integer: "; cin >> n; //Printing the number is prime or not if (checkPrimeNumber(n)) cout << n << " is a prime number."; else cout << n << " is not a prime number."; return 0; } bool checkPrimeNumber(int n) { //checking the [prime number] 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:-
In the above program, we have first initialized the required variable.
- no= it will hold the integer value of the input.
- i = it will hold the integer value.
- flag = it will hold the integer value.
Input message for the user for the integer value.
Program Logic Code.
Printing output prime number or not.