Write a Program to Check Whether the Given Number is Even or Odd in C++ using Function
Write a program to check whether the given number is even or odd in C++ using Function, If-else statement, and Ternary operator.
In this article, you will learn how to write a program to check whether the given number is even or odd in C++ using Function, If-else statement, and Ternary operator.
Example
7
The input number is odd.
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++ main()function
- C++ cinobject
- C++ coutobject
- C++ if-elsestatement
- C++ Functions
- C++ Ternary operator
What are even odd numbers?
If an integer number is divided by 2 If its reminder equals zero then it is an even number and if the remainder is greater than zero then it is an odd number.
Samples of Even & Odd Numbers
Odd Numbers: 1, 3, 5, 7, ...
In this article, we solve this problem in three methods:
Source Code
// Write a Program to Check Whether the Given Number is Even or Odd in C++ using If-else
#include <iostream>
using namespace std;
int main() {
    int x;
    
    cout << "Enter an integer number to check ::\n";
    cin >> x;
    
    if (x % 2 == 0) {
        cout << "The input number is even.\n";
    } else {
        cout << "The input number is odd.\n";
    }
    return 0;
}
Output
Enter an integer number to check ::
7
The input number is odd.
Explanation
In this given program, we have taken input 7 from the user then we checked that if the remainder is equal to zero It's an even number otherwise It's the odd number.
C++ Program to Check Whether Number is Even or Odd using Ternary Operator
// C++ Program to Check Whether Number is Even or Odd using Ternary Operator
#include <iostream>
using namespace std;
int main() {
    int x;
    
    cout << "Enter an integer number to check ::\n";
    cin >> x;
    
    x = x % 2 == 0 ? 1 : 0;
    
    if (x) {
        cout << "The input number is even.\n";
    } else {
        cout << "The input number is odd.\n";
    }
    return 0;
}
Output
Enter an integer number to check ::
6
The input number is even.C++ Program to Check Whether Number is Even or Odd using Function
// C++ Program to Check Whether Number is Even or Odd using Function
#include <bits/stdc++.h>
using namespace std;
// This function will check the number type
void CheckNumber(int x) {
    if (x % 2 == 0) {
        cout << "The input number is even.\n";
    } else {
        cout << "The input number is odd.\n";
    }
}
// It's the driver function
int main() {
    int x;
    
    cout << "Enter an integer number to check ::\n";
    cin >> x;
    CheckNumber(x);
    return 0;
}
Output
Enter an integer number to check ::
21
The input number is odd.
Also, visit these links
C Program to Check Whether a Number is Even or Odd