Even or Odd program in C++

In this example, you will write the c++ program to check whether the number entered by the user is even or odd.

When the number is completely divisible by 2 and the remainder is zero then the number is even. for example, 2, 4, 6, 8, 10, 12,  14, 16, 18, 20, etc are even number.

when a number is not divisible by 2 and has some remainder then the number is called an odd number. for example, 1, 3, 5, 7, 9, 11, 13, etc are odd number.

program to check even or odd using if else


#include <iostream>
using namespace std;

int main() {
  int num;

  cout << "Enter the number: ";
  /* take input from user */
  cin >> num;

  if ( num % 2 == 0)
    cout << num << " is even";
  else
    cout << num << " is odd";

  return 0;
}

output
Enter the number: 12
12 is even
Enter the number: 11
11 is odd

In the program, we have taken the integer number from the user and stored it in the variable num.

when if-statement is evaluated true i.e (num % 2) then print an even number and if not true, else part will get executed and print not even.


Check even or odd using ternary operator

In this program, we have used a ternary operator for finding even or odd instead of if-else.


#include <iostream>
using namespace std;

int main() {
  int num;

  cout << "Enter the number: ";
  cin >> num;
  
  // ternary operator
  (num % 2 == 0) ? cout << num << " is even" :  cout << num << " is odd";
    
  return 0;
}
output
Enter the number: 4
4 is even

Check even odd using class

In this example, we have used class for determining even or odd


#include<iostream>
using namespace std;

class StudyFame {
  private:
    int num;
  public:
    void getData();
    void EvenOdd();
};
void StudyFame::getData() {
  cout << "Enter the number: ";
  cin >> num;
};
void StudyFame::EvenOdd() {
  if ( num % 2 == 0)
    cout << num << " is even";
  else
    cout << num << " is odd";
};
int main() {
  StudyFame s;
  s.getData();
  s.EvenOdd();
  return 0;
}
output
Enter the number: 10
10 is even

Time Complexity of all above program is: O(1)