Number of sub arrays with odd sum | C ++ proggram to find count of sub - arrays with odd sum ; A temporary array of size 2. temp [ 0 ] is going to store count of even subarrays and temp [ 1 ] count of odd . temp [ 0 ] is initialized as 1 because there a single odd element is also counted as a subarray ; Initialize count . sum is sum of elements under modulo 2 and ending with arr [ i ] . ; i ' th ▁ iteration ▁ computes ▁ sum ▁ of ▁ arr [ 0 . . i ] ▁ ▁ under ▁ modulo ▁ 2 ▁ and ▁ increments ▁ even / odd ▁ count ▁ ▁ according ▁ to ▁ sum ' s value ; 2 is added to handle negative numbers ; Increment even / odd count ; An odd can be formed by even - odd pair ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOddSum ( int ar [ ] , int n ) { int temp [ 2 ] = { 1 , 0 } ; int result = 0 , val = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { val = ( ( val + ar [ i ] ) % 2 + 2 ) % 2 ; temp [ val ] ++ ; } result = ( temp [ 0 ] * temp [ 1 ] ) ; return ( result ) ; } int main ( ) { int ar [ ] = { 5 , 4 , 4 , 5 , 1 , 3 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " The ▁ Number ▁ of ▁ Subarrays ▁ with ▁ odd " " ▁ sum ▁ is ▁ " << countOddSum ( ar , n ) ; return ( 0 ) ; }