In this tutorial you will learn about the C++ Program to Display Prime Numbers Between Two Numbers Using Functions and its application with practical example.
C++ Program to Display Prime Numbers Between Two Numbers Using Functions
In this tutorial, we will learn to create a C++ program that will Display Prime Numbers Between Two Numbers Using Functions using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ programming.
- Conditional Statements in C++ programming.
- Arithmetic operations in C++ Programming.
Display Prime Numbers Between Two Numbers Using Functions:-
In today’s program, we will take the input range from the user to print the prime numbers between them. The prime numbers are those numbers that are only divisible by themselves. In c++ programming, we will check if that range has Prime Number or not and print those prime numbers.
With the help of this program, we can Display Prime Numbers Between Two Numbers Using Functions.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking the input number range from the user. 3. Calculating the prime numbers between a range. 4. Printing the result. 5. End the program. |
Program to Display Prime Numbers Between Two Numbers Using Functions:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <iostream> using namespace std; int checkPrimeNumber(int); int main() { //declaring the variables for the program. int n1, n2; bool flag; //taking the range for checking the prime numbers cout << "Enter two positive integers: "; cin >> n1 >> n2; // swapping n1 and n2 if n1 is greater than n2 if (n1 > n2) { n2 = n1 + n2; n1 = n2 - n1; n2 = n2 - n1; } cout << "Prime numbers between " << n1 << " and " << n2 << " are: "; for(int i = n1+1; i < n2; ++i) { // If i is a prime number, flag will be equal to 1 flag = checkPrimeNumber(i); if(flag) cout << i << " "; } return 0; } // user-defined function to check prime number int checkPrimeNumber(int n) { bool isPrime = true; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { isPrime = false; } else { for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { isPrime = false; break; } } } return isPrime; } |
Output:-
In the above program, we have first initialized the required variable.
- n1= it will hold the integer value of the input.
- n2 = it will hold the integer value of the input.
- flag = it will hold the boolean value.
Input message for the user for the integer value range.
Program Logic Code user-defined function.
Printing output prime number or not.