Checking Prime Numbers By Making Functions In C++

Exercise:

Write a C++ program to check for prime numbers using user-defined functions.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int TestPrimeNumber(int);
int main()
{
    int num1, num2;
    bool check;
    cout << "Insert the initial and final interval of the prime numbers:\n";
    cin >> num1 >> num2;
    // swapping n1 and n2 if n1 is greater than n2
    if (num1 > num2)
    {
        num2 = num1 + num2;
        num1 = num2 - num1;
        num2 = num2 - num1;
    }
    cout << "Prime numbers between " << num1 << " and " << num2 << " are: ";
    for(int x = num1+1; x < num2; ++x)
    {
        // If x is a prime number, check will be equal to 1
        check = TestPrimeNumber(x);
        if(check)
        cout << x << " ";
    }
    return 0;
}
// user-defined function to check prime number
int TestPrimeNumber(int t)
{
    bool Prime = true;
    // 0 and 1 are not prime numbers
    if (t == 0 || t == 1)
    {
        Prime = false;
    }
    else 
    {
        for(int y = 2; y <= t/2; ++y)
        {
            if (t%y == 0)
            {
                Prime = false;
                break;
            }
        }
    }
    return Prime;
}
Click Here to View the Output:
Insert the initial and final interval of the prime numbers:
23
87
Prime numbers between 23 and 87 are: 29 31 37 41 43 47 53 59 61 67 71 73 79 83
Click Here to View the Explanation:
  • A boolean type variable is declared check.
  • The function TestPrimeNumber () is created. It is marked false if the number is not a prime number and true otherwise.
  • The code for checking the prime number is inserted in the new function.
  • The function is then called in the main () function. If it is true, It is a prime number. is displayed on the screen.
%d bloggers like this: