Programming Tutorials

Checking Prime Number in C++

By: Grant Braught in C++ Tutorials on 2011-01-27  

This sample C++ program, simply accespt a number and indicates whether it is a Prime number or not a prime number.
#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;	
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)