Algorithm
1. Start
2. Read the lower limit (lower) and upper limit (upper) of the interval from the user.
3. Display "Prime numbers between [lower] and [upper] are:".
4. For each number i in the range from lower to upper:
a. Initialize a boolean variable isPrime to true.
b. If i is less than 2, set isPrime to false.
c. For each number j in the range from 2 to the square root of i:
i. If i is divisible by j, set isPrime to false and break the loop.
d. If isPrime is true, display i as a prime number.
5. End
Code Examples
#1 Code Example- C++ programing Display Prime Numbers Between two Intervals
Code -
C++ Programming
#include <iostream>
using namespace std;
int main() {
int low, high, i;
bool is_prime = true;
cout << "Enter two numbers (intervals): ";
cin >> low >> high;
cout << "\nPrime numbers between " << low << " and " << high << " are: " << endl;
while (low < high) {
is_prime = true;
// 0 and 1 are not prime numbers
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;
}
Copy The Code &
Try With Live Editor
Output
20
Prime numbers between 0 and 20 are:
2, 3, 5, 7, 11, 13, 17, 19,
#2 COde Example- Display Prime Numbers When Larger Number is Entered first
Code -
C++ Programming
#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;
}
Copy The Code &
Try With Live Editor
Output
0
Prime numbers between 0 and 20 are:
2, 3, 5, 7, 11, 13, 17, 19,
Demonstration
C++ Programing Example to Display Prime Numbers Between Two Intervals-DevsEnv