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

#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

Recommended Posts
C++ Program to Check Prime Number
C++ Program to Find GCD of Two Numbers
C++ Program to Check for Armstrong Number
C++ Program to Display Armstrong Number Between Two Intervals
C++ Program to Multiply Two Matrices
C++ Program to Add Two Matrix
C++ Program to Count Words in Sentence
C++ Program to Reverse Digits of a Number
C++ Program to Print All Prime Numbers Between 1 to N
C++ Program to Check Leap Year
C++ Program to Make a Simple Calculator
All C++ Programs