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

C++ProgrammingServer Side Programming

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are 2, 3, 5, 7, 11, 13 ,17 etc.

There can be many prime numbers between two intervals. For example, the prime numbers between the intervals 5 and 20 are 5, 7, 11, 13, 17 and 19.

The program to find and display the prime numbers between two intervals is given as follows.

## Example

Live Demo

#include <iostream>
using namespace std;
void primeNumbers (int lbound, int ubound) {
int flag, i;
while (lbound <= ubound) {
flag = 0;
for(i = 2; i <= lbound/2; i++) {
if(lbound % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout<<lbound<<" ";
lbound++;
}
}
int main() {
int lowerbound = 20, upperbound = 50;
cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
return 0;
}

## Output

Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47

In the above program, the function main() contains only the cout object and the function call to the function primeNumbers() with upperbound and lowerbound as arguments. This can be seen in the following code snippet.

cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
primeNumbers(lowerbound,upperbound);

In the function primeNumbers(), each number from lbound to ubound is tested to see if it is prime or not. If it is a prime number, it is displayed. This is done using a while loop.

In the while loop, initial value of flag=0. If the number is not prime, then the value of flag is set to 1 in the for loop. After the end of the for loop, if flag is still 0, then the number is prime and it is displayed. This can be observed from the following code snippet.

while (lbound <= ubound) {
flag = 0;
for(i = 2; i <= lbound/2; i++) {
if(lbound % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout<<lbound<<" ";
lbound++;
}
Published on 27-Sep-2018 13:01:40