Q2. Check if a number is a prime number

Q2. Check if a number is a prime number using a function

Note on booleans in C++

boolean variables can be declared using the bool keyword
For example,

bool bPrime = true;

Read the following code carefully to understand how to use booleans in C++

Solution

/* primetester.cpp */
 
#include <iostream>
using namespace std;
 
//function prototype declaration
bool isPrime(int number);
 
int main() {
    int num = 0;
 
    cout << "Enter a number:";   //display prompt to the user
    cin >> num;                  //read the number from the keyboard
 
    bool bPrime = isPrime(num);  //call the isPrime function 
    cout << "bPrime:" << bPrime << endl; //if false print 0 - if true prints 1
 
    if(bPrime == true)              //print whether the number is prime or not
        cout << num << " is a prime number" << endl;
    else
        cout << num << " is not a prime number" << endl;
 
    system("pause"); //this stops the output window from closing automatically
}
 
bool isPrime(int number) {
     bool bPrime = true; //assume that the number is prime 
 
     //now test if the number is actually a prime number
     for (int i = 2 ; i < number ; i++) {
         if (number % i == 0) {
            //number is not prime - set bPrime to false  
            bPrime = false;
            //and come out of the loop using break
            break;
         }
     }
 
     return bPrime;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License