Home »
C++ Programs
C++ program to check if the number is odd or even using class
Given a number, we have to check whether it is even or odd using class and object approach.
Submitted by Shubh Pachori, on August 05, 2022
Problem statement
Given a number, we have to check whether it is even or odd using class and object approach.
Example:
Input: 1234
Output: 1234 is an even number
C++ code to check EVEN or ODD using class and object approach
#include <iostream>
using namespace std;
// create a class
class OddOrEven {
// a int type private data member
private:
int number;
// a public function with an int type parameter
public:
void oddoreven(int n) {
// copying values of parameters in data members
number = n;
// if condition to check if a number is even by dividing it by 2
if (number % 2 == 0) {
cout << number << " is an even number." << endl;
}
// else to return if it is not even then it is odd
else {
cout << number << " is an odd number." << endl;
}
}
};
int main() {
// create a object
OddOrEven O;
// an int type variable to store number
int number;
cout << "Enter Number: ";
cin >> number;
// calling function using object
O.oddoreven(number);
return 0;
}
Output
RUN 1:
Enter Number: 131
131 is an odd number.
RUN 2:
Enter Number: 2460
2460 is an even number.
Explanation
In the above code, we have created a class OddOrEven, one int type data member number to store the number, and a public member function oddoreven() to check the given integer number.
In the main() function, we are creating an object O of class OddOrEven, reading an integer number by the user, and finally calling the oddoreven() member function to check the given integer number. The oddoreven() function contains the logic to check the given number whether it is odd or even and printing the result.
C++ Class and Object Programs (Set 2) »