C++ program to display prime numbers between two intervals using function
In this article, you will learn how to print the prime numbers between two intervals using the function in the c++ programming language.
You should have knowledge of the following topics in c++ programming to understand this program:
- C++ functions
- C++
main
function - C++
for
loop statement - C++
if
condition statement - C++
continue
statement - C++
cin
object - C++
cout
object
In this program, we are using a user-defined
function to find the prime numbers of the given two intervals.
Source Code
// C++ program to display prime numbers between two intervals using function
#include <bits/stdc++.h>
using namespace std;
// @custom function to find the prime numbers between intervals
int GeneratePrimeNumbers(int low_number, int high_number) {
int flag, temp;
// this will swap the value of intervals between each other
// if low_number is greater then high_number
if (low_number > high_number) {
temp;
temp = low_number;
low_number = high_number;
high_number = temp;
}
cout << "\nThe prime numbers between " << low_number << " and " << high_number << " are: ";
for (int i = low_number; i <= high_number; i++) {
flag = 0;
// this will ignore numbers less than 2
if (i <= 1) {
continue;
}
// if low_number is a non-prime number, flag will be 1
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout << i << " ";
}
cout << "\n";
return 0;
}
// @driver function to call & print the primer numbers
int main() {
int low_number, high_number;
cout << "Enter the two intervals:\n";
cin >> low_number >> high_number;
// @call the custom function to print the numbers
GeneratePrimeNumbers(low_number, high_number);
return 0;
}
Output
Enter the two intervals:
10 40
The prime numbers between 10 and 40 are: 11 13 17 19 23 29 31 37
Note: We swapped the value of the interval between each other if low_number
is greater than high_number
.
Explanation
In this given program we used a user-defined function to find the primer numbers between two intervals.
so first we have taken two inputs 16
and 35
from the user then these values pass to this function GeneratePrimeNumbers()
after making the calculation it returned the list of prime numbers.