Write a C++ Program to Display Prime Numbers Between Two Intervals Using Functions

As a C++ programmer, you might come across the requirement to display prime numbers between two intervals.

In this tutorial, we will go through a C++ program to display prime numbers between two intervals using functions.

Before diving into the program, let’s understand the concept of prime numbers.

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are prime numbers.

Now, let’s move on to the program.

First, we will create a function called “isPrime” that will take a number as an argument and return true if the number is prime, and false if the number is not prime.

The function will implement a simple algorithm to check if the number is prime or not.

It will iterate from 2 to the square root of the number and check if the number is divisible by any of the numbers in the range.

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;
}

Now, we will create another function called “displayPrimes” that will take two arguments, start and end, and display all the prime numbers between the two intervals.

The function will call the “isPrime” function to check if a number is prime and then print it if it is.

void displayPrimes(int start, int end) {
  for (int i = start; i <= end; i++) {
    if (isPrime(i)) {
      cout << i << " ";
    }
  }
}

Finally, in the main function, we will take input for the start and end intervals and call the “displayPrimes” function to display all the prime numbers between the two intervals.

int main() {
  int start, end;

  cout << "Enter the start and end intervals: ";
  cin >> start >> end;

  cout << "Prime numbers between " << start << " and " << end << " are: ";
  displayPrimes(start, end);

  return 0;
}

That’s it! We have successfully created a program to display prime numbers between two intervals using functions.

In conclusion, displaying prime numbers between two intervals is a common requirement in C++ programming.