Count subarrays having sum of elements at even and odd positions equal | Java program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Size of the array ; Function call
import java . util . * ; class GFG { static void countSubarrays ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( ( j - i ) % 2 == 0 ) sum += arr [ j ] ; else sum -= arr [ j ] ; if ( sum == 0 ) count ++ ; } } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 4 , 2 } ; int n = arr . length ; countSubarrays ( arr , n ) ; } }