C++ Program to Check Prime Number Using User-defined Function

In the previous article, we have discussed C++ Program to Display Armstrong Number Between Two Intervals. In this article, we will see C++ Program to Check Prime Number Using User-defined Function.

C++ Program to Check Prime Number Using User-defined Function

  • C++ Program to Check Prime Number Using User-defined Function

C++ Program to check prime numbers using function

C++ Program to check prime numbers using function 1

#include<iostream>
 
using namespace std;
  
int isPrime(int num);
 
int main() {
  int num;
  cout << "Enter a positive number\n";
  cin >> num;
    
  if(isPrime(num))
      cout << num << " is a Prime Number",num);
  else
      cout << num <<" is NOT a Prime Number",num);
        
  return 0;
}
 
// returns 1 if num is prime number otherwise 0
int isPrime(int num){
    int i;
    // Check whether num is divisible by any 
    // number between 2 to (num/2)
    for(i = 2; i <=(num/2); ++i) {
        if(num%i==0) {
            return 0;
        }
    }
    return 1;
}

Output

Enter a positive number
23
23 is a Prime Number
Enter a positive number
50
50 is NOT a Prime Number

We know that C++ is an object oriented programming language. The advanced C++ Topics are enumerated constants, multi-dimensional arrays, character arrays, structures, reading and writing files and many more. Check the complete details of all those from this article.