C++ - Program - Prime Numbers

#include <iostream>
// Function to check if a number is prime
bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}
// Function to display prime numbers within a range
void displayPrimes(int start, int end) {
    std::cout << "Prime numbers between " << start << " and " << end << " are: ";
    for (int i = start; i <= end; i++) {
        if (isPrime(i)) {
            std::cout << i << " ";
        }
    }
    std::cout << std::endl;
}
int main() {
    int start, end;
    std::cout << "Enter the range (start and end): ";
    std::cin >> start >> end;
    // Display prime numbers within the given range
    displayPrimes(start, end);
    return 0;
}

In this program, we define two functions: isPrime and displayPrimes.

The isPrime function takes an integer num as input and checks if it is a prime number. It returns true if the number is prime and false otherwise. The function uses a for loop to iterate from 2 to the square root of num and checks if num is divisible by any number within that range. If it is divisible by any number, it is not a prime number.

The displayPrimes function takes two integers start and end as input, representing the range of numbers. It displays all the prime numbers within that range. It uses a loop to iterate through each number in the range and calls the isPrime function to check if the number is prime. If it is prime, it is displayed on the console.

In the main function, we prompt the user to enter the range (start and end) of numbers. The input is stored in the variables start and end. We then call the displayPrimes function to display the prime numbers within the given range.