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

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) »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.