Check in binary array the number represented by a subarray is odd or even


Given a array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even


Input : arr = {1, 1, 0, 1}
        l = 1, r = 3
Output : odd
        number represented by arr[l...r] is 
        101 which 5 in decimal form which is 

Input :  arr = {1, 1, 1, 1}
         l = 0, r = 3
Output : odd

The important point to note here is all the odd numbers in binary form have 1 as their rightmost bit and all even numbers have 0 as their rightmost bit.
The reason is simple all other bits other than rightmost bit have even values and sum of even numbers is always even .Now the rightmost bit can have value either 1 or 0 as we know even + odd = odd so when right most bit is 1 the number is odd and when it is 0 the number is even.
So to solve this problem we have to just check if a[r] is 0 or 1 and accordingly print odd or even

// C++ program to find if a subarray
// is even or odd.
using namespace std;

// prints if subarray is even or odd
void checkEVENodd (int arr[], int n, int l, int r)
    // if arr[r] = 1 print odd
    if (arr[r] == 1)
        cout << "odd" << endl;

    // if arr[r] = 0 print even
        cout << "even" << endl;

// driver code
int main()
    int arr[] = {1, 1, 0, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
    checkEVENodd (arr, n, 1, 3);
    return 0;



This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

1.5 Average Difficulty : 1.5/5.0
Based on 18 vote(s)

Writing code in comment? Please use, generate link and share the link here.