Count subarrays having sum of elements at even and odd positions equal | Function to count subarrays in which sum of elements at even and odd positions are equal ; Initialize variables ; Iterate over the array ; Check if position is even then add to sum then add it to sum ; Else subtract it to sum ; Increment the count if the sum equals 0 ; Print the count of subarrays ; Given array arr [ ] ; Size of the array ; Function call
function countSubarrays ( arr , n ) { var count = 0 ; var i , j ; for ( i = 0 ; i < n ; i ++ ) { var sum = 0 ; for ( j = i ; j < n ; j ++ ) { if ( ( j - i ) % 2 == 0 ) sum += arr [ j ] ; else sum -= arr [ j ] ; if ( sum == 0 ) count ++ ; } } document . write ( count ) ; } var arr = [ 2 , 4 , 6 , 4 , 2 ] ; var n = arr . length ; countSubarrays ( arr , n ) ;