Printing All Prime Numbers Between two Intervals With Functions In C++

Exercise:

Write a C++ program to print all prime numbers between an interval of two provided numbers using functions.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int scanPrime(int);
int main() 
{
    int num1, num2;
    bool check;
    cout << "Insert any two positive numbers:\n";
    cin >> num1 >> num2;
    // 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 i = num1+1; i < num2; ++i)
    {
        // If i is a prime number, check will be equal to 1
        check = scanPrime(i);
        if(check)
        cout << i << " ";
    }
    return 0;
}
// user-defined function to check prime number
int scanPrime(int num)
{
    bool prime = true;
    // 0 and 1 are not prime numbers
    if (num == 0 || num == 1)
    {
        prime = false;
    }
    else 
    {
        for(int j = 2; j <= num/2; ++j)
        {
            if (num%j == 0)
            {
                prime = false;
                break;
            }
        }
    }
    return prime;
}
Click Here to View the Output:
Insert any two positive numbers:
32
89
Prime numbers between 32 and 89 are: 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 scanPrime ( ) 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.
  • All the numbers num1, num2, etc. cross through this function using a for loop.
  • When the number is a prime number, the value returns true, and is printed on the screen.
  • Otherwise, the value returns 0 and the for loop is terminated.
  • The function is then called in the main () function.
  • To further improve the code, another function can be created/ step can be added to swap numbers in case the user enters the larger number of the interval before the smaller number.