Use the bitwise operator, &, to test the number to see if it is even or odd - C++ Operator

C++ examples for Operator:Bit Operator

Introduction

If the bit on the extreme right in input is 1, tell the user that the number is odd.

If the bit on the extreme right in input is 0, tell the user that the number is even.

Demo Code


#include <iostream>
using namespace std;
int main()//from ww  w.  jav  a 2s  .  c o  m
{
    int input;                    // Will hold user's number
    cout << "What number do you want me to test? ";
    cin >> input;
    if (input & 1)              // True if result is 1; // otherwise it is false (0)
    {
       cout << "The number " << input << " is odd\n";
    }
    else
    {
       cout << "The number " << input << " is even\n";
    }
    return 0;
}

Result


Related Tutorials