C++ Program to Display Prime Numbers Between Two Intervals

Example to print all prime numbers between two numbers (entered by the user) in C++ Programming. This problem is solved using nested for loop and if…else statement.

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

• C++ if, if…else and Nested if…else
• C++ for Loop
• C++ break and continue Statement

Example #1: Display Prime Numbers Between two Intervals

#include <iostream>
using namespace std;

int main()
{
int low, high, i, flag;

cout << "Enter two numbers(intervals): ";
cin >> low >> high;

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

while (low < high)
{
flag = 0;

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

if (flag == 0)
cout << low << " ";

++low;
}

return 0;
}

Output

Enter two numbers(intervals): 20 50 Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47

In this program, the while loop is iterated (high - low - 1) times.

In each iteration, whether low is a prime number or not is checked and the value of low is incremented by 1 until low is equal to high.

If the user enters larger number first, this program doesn’t work as intended. You can solve this issue by swapping the numbers if the user enters larger number first.

Example #2: Display Prime Numbers When Larger Number is Entered first

#include <iostream>
using namespace std;

int main()
{
int low, high, flag, temp;

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 << "Prime numbers between " << low << " and " << high << " are: ";

while (low < high)
{
flag = 0;

for(int i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout << low << " ";

++low;
}
return 0;
}