Google News
logo
C++ Program to Display Prime Numbers Between Two Intervals
In the following example of C++ program that displays all the prime numbers between two given intervals :
Program :
#include <iostream>

using namespace std;

int main()
{
    int low, high, i, j, is_prime;

    cout << "Enter two positive integers: ";
    cin >> low >> high;

    cout << "Prime numbers between " << low << " and " << high << " are: " << endl;

    // Loop through each number between low and high
    for (i = low; i <= high; i++) {
        // Assume the number is prime
        is_prime = 1;

        // Check if the number is divisible by any number from 2 to i/2
        for (j = 2; j <= i/2; j++) {
            if (i % j == 0) {
                // If the number is divisible, it is not prime
                is_prime = 0;
                break;
            }
        }

        // If the number is prime, print it to the console
        if (is_prime) {
            cout << i << endl;
        }
    }

    return 0;
}
Output :
Enter two positive integers: 2
30
Prime numbers between 2 and 30 are: 
2
3
5
7
11
13
17
19
23
29
In this program, we first prompt the user to enter two positive integers using cout. We then read the integer inputs using cin.

We then use a loop to iterate over each number between the two integers. For each number, we assume it is prime by setting the is_prime variable to 1. We then check if the number is divisible by any number from 2 to half of the number using another loop. If the number is divisible by any of these numbers, we set the is_prime variable to 0 and break out of the loop.

After the inner loop, we check if the is_prime variable is still 1. If it is, we print the number to the console using cout.

At the end of the program, we return 0 to indicate successful execution.
Program :
 

Display Prime Numbers When Larger Number is Entered first :

#include <iostream>
using namespace std;

int main() {

  int low, high, temp, i;
  bool is_prime;
    
  cout << "Enter two numbers (intevals): ";
  cin >> low >> high;

  //swapping numbers if low is greater than high
  if (low > high) {
    temp = low;
    low = high;
    high = temp;
  }

  cout << "\nPrime numbers between " << low << " and " << high << " are:" << endl;

  while (low < high) {
    is_prime = true;


    if (low == 0 || low == 1) {
      is_prime = false;
    }

    for (i = 2; i <= low / 2; ++i) {
      if (low % i == 0) {
        is_prime = false;
        break;
      }
    }

    if (is_prime)
      cout << low << ", ";

    ++low;
  }

  return 0;
}

 

Output :
Enter two numbers (intevals): 30
2
Prime numbers between 2 and 30 are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,