Home »
C++ Programs
C++ program to print even numbers in a range using class
Submitted by Shubh Pachori, on August 14, 2022
Problem statement
Given a range, we have to print all even numbers in that range using the class and object approach.
Example:
Input:
Enter Range: 2 9
Output:
Even Numbers in the range 2 to 9 are
2 4 6 8
C++ code to print even numbers in a range using class and object approach
#include <iostream>
using namespace std;
// create a class
class IsEven {
// declare private data members
private:
int start, end;
// public functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Range: ";
cin >> start >> end;
}
// isEven() function to print even numbers in between
// range
void isEven() {
// initilaize int type variable for indexing
int index_1;
cout << "Even Numbers in the range " << start << " to "
<< end << " are " << endl;
// for loop to search even number in the range
for (index_1 = start; index_1 <= end; index_1++) {
// if the index_1 is completely divided by 2
if (index_1 % 2 == 0) {
cout << index_1 << " ";
}
}
}
};
int main() {
// create a object
IsEven E;
// calling getRange() function to insert range
E.getRange();
// isEven() function search even numbers in the range
E.isEven();
return 0;
}
Output
RUN 1:
Enter Range: 1 100
Even Numbers in the range 1 to 100 are
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36
38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68
70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
RUN 2:
Enter Range: 11 21
Even Numbers in the range 11 to 21 are
12 14 16 18 20
Explanation
In the above code, we have created a class IsEven, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isEven() to store and print even numbers in between that given range.
In the main() function, we are creating an object E of class IsEven, reading a range by the user using getRange() function, and finally calling the isEven() member function to print the even numbers in the given range. The isEven() function contains the logic to print even numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »