Program to Find Prime Numbers in a Given Range in C++
Finding Prime Numbers in a Range
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
We will explore different methods to find all prime numbers within a given range using C++ programming.
Method 1: Using a for Loop
We iterate through the given range and check if each number is prime.
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
int main() {
int start, end;
cout << "Enter the range (start end): ";
cin >> start >> end;
cout << "Prime numbers between " << start << " and " << end << " are: ";
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
return 0;
}
Output:
Enter the range (start end): 10 20 Prime numbers between 10 and 20 are: 11 13 17 19