beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C++ Program to Check Prime Number using Function

By Chaitanya Singh | Filed Under: C++ Programs

A number which is only divisible by itself and 1 is known as prime number. For example 13 is a prime number because it is only divisible by itself and 1, while 14 is not a prime number because it is divisible by 2 and 7 along with the number itself and 1.

This program takes the input number and checks whether the number is prime number or not using a function.

Checking prime number using function

In this program, we have created a function called isPrime(int) which takes integer number as input and returns a boolean value true or false.

The program takes the value of num (entered by user) and passes this value while calling isPrime() function. This function checks whether the passed value is prime or not, if the value is prime then it returns true, else it returns false.
If you are looking for a program that checks the prime number without using functions then see: C++ Program to check prime number using loops.

#include <iostream>
using namespace std;
bool isPrime(int num);

int main(){
   int num;
   bool flag;
   cout<<"Enter any number(should be positive integer): ";
   cin>>num;
   flag = isPrime(num);
   if (flag==true)
      cout<<num<<" is a prime number";
   else
      cout<<num<<" is not a prime number";
   return 0;
}
bool isPrime(int num){
    bool flag=true;
    for(int i = 2; i <= num / 2; i++) {
       if(num % i == 0) {
          flag = false;
          break;
       }
    }
    return flag;
}

Output:

Enter any number(should be positive integer): 9
9 is not a prime number

Enjoyed this post? Try these related posts

  1. C++ Program to find number of Vowels and Consonants in a String
  2. C++ Program to Add two Times entered by User
  3. C++ Program to Convert Lowercase to Uppercase
  4. C++ Program to display Armstrong Numbers between 1 and 1000
  5. C++ Program to add two numbers
  6. C++ Program for Binary Search

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap