Primes in Range in C++
List primes in a range in C++. 10 to 30: 11 13 17 19 23 29. Reuses the sqrt test.
1#include <iostream>2#include <cmath>3using namespace std;45bool isPrime(int n) {6 if (n <= 1) return false;7 for (int i = 2; i <= sqrt(n); i++) {8 if (n % i == 0) return false;9 }10 return true;11}1213int main() {14 int start, end;1516 cout << "Enter start of range: ";17 cin >> start;1819 cout << "Enter end of range: ";20 cin >> end;2122 cout << "Prime numbers between " << start << " and " << end << " are: ";2324 for (int i = start; i <= end; i++) {25 if (isPrime(i)) {26 cout << i << " ";27 }28 }29 cout << endl;3031 return 0;32}
Output
Enter start of range: 10 Enter end of range: 30 Prime numbers between 10 and 30 are: 11 13 17 19 23 29
What's going on
This C++ program lists every prime from start to end. 10 to 30: 11 13 17 19 23 29.
bool isPrime(int n) is the same test as Prime Check, pulled into a function so the range loop stays readable.
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) if n % i == 0 return false.
Otherwise true.
cin >> start; cin >> end;
Sample 10 and 30.
for (int i = start; i <= end; i++)
if (isPrime(i)) cout << i << " ";
10 is not prime (2×5). 11 is. The line ends with a space before endl. Harmless.
start > end: the loop never runs. You still print the "are:" label and a blank list.
A sieve is faster for huge ranges. For 10–30 this is fine. Don't copy-paste the prime test into the loop body — that's how the <= 1 check gets forgotten on the second copy.