×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to check prime number

Given an integer number, we have to check whether it is a primer number or not using C++ program.
[Last updated : February 28, 2023]

Problem statement

Prime numbers are those numbers which are divisible by itself only. In this program, we will learn how to check whether a given number is prime or not?

Checking prime number in C++

To check prime number, read an integer number and check whether it is Prime or Not, to check prime number we implemented a function isPrime() that will take integer number as argument and return 1 if it is primer else it return 0.

Program to check prime number in C++

#include <iostream>
using namespace std;

//function declaration
int isPrime(int n);

int main()
{
    int num;

    cout << "Enter an integer number: ";
    cin >> num;

    if (isPrime(num))
        cout << num << " is a prime number" << endl;
    else
        cout << num << " is not a prime number" << endl;

    return 0;
}

//function definition
int isPrime(int n)
{
    int i;
    int prime = 1;

    for (i = 2; i < (n / 2); i++) {
        if (n % i == 0) {
            prime = 0;
            break;
        }
    }
    return prime;
}

Output

First run:
Enter an integer number: 120
120 is not a prime number

Second run:
Enter an integer number: 111
111 is not a prime number

Third run:
Enter an integer number: 97
97 is a prime number

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.