Checking Prime Number in C++

By: Grant Braught Viewed: 153302 times  Printer Friendly Format    


This sample C++ program, simply accespt a number and indicates whether it is a Prime number or not a prime number.
#include 

// 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;	
}


Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial