Q:

C++ program to check prime number

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to display prime numbers... >>
<< C++ program to find factorial of a number...