Home »
C++ Programs
C++ program to print prime numbers in a range using class
Submitted by Shubh Pachori, on August 14, 2022
Problem statement
Given a range, we have to print all prime numbers in that range using the class and object approach.
Example:
Input:
Enter Range: 11 34
Output:
Prime Numbers in the range 11 to 34 are
11 13 17 19 23 29 31
C++ code to print prime numbers in a range using class and object approach
#include <iostream>
using namespace std;
// create a class
class IsPrime {
// declare private data members
private:
int start, end;
// public functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Range:";
cin >> start >> end;
}
// isPrime() function to print prime numbers in between range
void isPrime() {
// initilaize two int type variable for indexing
int index_1, index_2;
cout << "Prime Numbers in the range " << start << " to " << end << " are " << endl;
// for loop to search prime number in the range
for (index_1 = start; index_1 <= end; index_1++) {
// counter variable
int check = 0;
// for loop for checking if the number is prime or not
for (index_2 = 2; index_2 < index_1; index_2++) {
// if condition to check if the index_1 is divisible by the index_2
if (index_1 % index_2 == 0) {
// counter increased by 1
check++;
// break statement to break the loop
break;
}
}
// if the counter is zero then the index_1 number is printed
if (check == 0) {
cout << index_1 << " ";
}
}
}
};
int main() {
// create a object
IsPrime P;
// calling getRange() function to insert range
P.getRange();
// IsPrime() function search prime numbers in the range
P.isPrime();
return 0;
}
Output
Enter Range:9 25
Prime Numbers in the range 9 to 25 are
11 13 17 19 23
Explanation
In the above code, we have created a class IsPrime, two int-type data members start and end to store the start and end of the range, and public member functions getRange() and isPrime() to store and print prime numbers in between that given range.
In the main() function, we are creating an object P of class IsPrime, reading a range by the user using getRange() function, and finally calling the isPrime() member function to print the prime numbers in the given range. The isPrime() function contains the logic to print prime numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »