C++ Program to Display Prime Numbers Between Two Intervals Using Functions

To understand this example, you should have the knowledge of the following C++ programming topics:


Example: Prime Numbers Between two Intervals

// C++ Program to Print Prime Numbers between two Numbers

#include <iostream>
bool isPrime(int);
void printPrime(int num1, int num2);

int main(){
    int num1, num2;
    std::cout << "Enter two positive integers: ";
    std::cin >> num1 >> num2;
    printPrime(num1, num2);
}
// prints the prime number between num1 and num2
void printPrime(int num1, int num2){
    if (num1 > num2){
       // swap if num1 is greater than num2
        std::swap(num1, num2);
    }
    for(int i = num1 + 1 ; i < num2 ; ++i){
        if (isPrime(i)){
            std::cout << i << " ";
        }
    }
}
// returns true is the given number is true false otherwise
bool isPrime(int n){
    bool is_prime = true;
    // 0 and 1 are not prime numbers
    if (n == 0 || n == 1) {
       return false;
    }
    for(int i = 2; i <= n/2; ++i) {
      if (n % i == 0) {
         return false;
      }
    }
  return is_prime;
}

Output

Enter two positive integers: 12
55
Prime numbers between 12 and 55 are:
13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53

To print all prime numbers between two integers, the printPrime() function is created. Internally it calls the isPrime function which checks whether a number is prime or not.

All integers between n1 and n2 are passed to the isPrime function.

If a number passed to isPrime() is a prime number, this function returns true and the number will be written to standard output, otherwise the function returns false and no action is taken.

If the user enters the larger number first, this program will first swap the numbers. This program won't work without swapping because, inside the for loop of printPrime function assumes that num1 is always greater than num2.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges