Primes in Range

Program to find all prime numbers in a given range

IntermediateTopic: Loop Programs
Back

C++ Primes in Range Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    int start, end;
    
    cout << "Enter start of range: ";
    cin >> start;
    
    cout << "Enter end of range: ";
    cin >> end;
    
    cout << "Prime numbers between " << start << " and " << end << " are: ";
    
    for (int i = start; i <= end; i++) {
        if (isPrime(i)) {
            cout << i << " ";
        }
    }
    cout << endl;
    
    return 0;
}
Output
Enter start of range: 10
Enter end of range: 30
Prime numbers between 10 and 30 are: 11 13 17 19 23 29

Understanding Primes in Range

This program finds all prime numbers in a range. We use a helper function isPrime() to check if each number in the range is prime. The function uses the square root optimization for efficiency. We iterate through the range and print all prime numbers.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents