Home » C++ programs » C++ Most popular & searched programs

C++ program to check prime number

In this program, we will learn how to check whether a given number is prime or not?

Prime numbers are those numbers which are divisible by itself only. Here, we will 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.