C++ Bitwise Operator & test the number to see if it is even or odd

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.


#include <iostream>
using namespace std;
int main()/*from   w  w w . j  a  v  a2 s  .  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;
}



PreviousNext

Related