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.

IntermediateLoop ProgramsExample 9 of 14
primes-in-range.cpp
1#include <iostream>
2#include <cmath>
3using namespace std;
4
5bool 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}
12
13int main() {
14 int start, end;
15
16 cout << "Enter start of range: ";
17 cin >> start;
18
19 cout << "Enter end of range: ";
20 cin >> end;
21
22 cout << "Prime numbers between " << start << " and " << end << " are: ";
23
24 for (int i = start; i <= end; i++) {
25 if (isPrime(i)) {
26 cout << i << " ";
27 }
28 }
29 cout << endl;
30
31 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.