In this C++ tutorial, you will learn how to write a program to display the prime numbers between two given numbers.
C++ Prime numbers between two numbers
To find the prime numbers between two given numbers in C++, we iterate from the smallest number to the highest number in increment of one, and check if the number is prime or not.
Program
In the following program, we read two numbers to n1 and n2, and print the prime numbers present in the interval formed by these two numbers. We shall use C++ While Loop for iteration.
C++ Program
</>
Copy
#include <iostream>
using namespace std;
bool isPrime(int n) {
bool isPrime = true;
if (n == 0 || n == 1) {
isPrime = false;
}
else {
int i = 0;
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
return isPrime;
}
int main() {
int n1, n2;
cout << "Enter first number : ";
cin >> n1;
cout << "Enter second number : ";
cin >> n2;
int temp = (n1 > n2)? n2: n1;
int upperlimit = (n1 > n2)? n1: n2;
cout << "Prime Numbers : ";
while (temp < upperlimit) {
if (isPrime(temp)) {
cout << temp << " ";
}
temp++;
}
cout << endl;
}
Output
Enter first number : 10
Enter second number : 25
Prime Numbers : 11 13 17 19 23
Program ended with exit code: 0
Enter first number : 30
Enter second number : 5
Prime Numbers : 5 7 11 13 17 19 23 29
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to display prime numbers in given interval in C++, with example program.