#include <iostream>
// Prototype for IsPrime function.
bool IsPrime(int);
// main function is always run first in a
// C++ program.
int main()
{ //Given: nothing.
//Results: Accepts a number and
// indicates if it is prime.
int number;
cout << "Enter an integer (>1): ";
cin >> number;
if (IsPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
// This is more convention than anything.
return 0;
}
bool IsPrime(int number)
{ // Given: num an integer > 1
// Returns: true if num is prime
// false otherwise.
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
C++ / PRACTICAL TUTORIAL
Checking Prime Number in C++
Advertisement
This sample C++ program, simply accespt a number and indicates whether it is a Prime number or not a prime number.
From the community
No archived comments on this tutorial.