Easy Tutorial
❮ Returning Values By Reference Cpp Variable Scope ❯

C++ Example - Determine if a Number is Odd or Even

C++ Examples

Below, we use the modulo operator % to determine if a number is odd or even. The principle is that if the number divided by 2 has a remainder of 0, it is even; otherwise, it is odd.

Example - Using if...else

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter an integer: ";
    cin >> n;

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

    return 0;
}

The output of the above program is:

Enter an integer: 5
5 is odd.

Example - Using the Ternary Operator

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter an integer: ";
    cin >> n;

    (n % 2 == 0) ? cout << n << " is even." :  cout << n << " is odd.";

    return 0;
}

The output of the above program is:

Enter an integer: 5
5 is odd.

C++ Examples

❮ Returning Values By Reference Cpp Variable Scope ❯