Number of subarrays having sum exactly equal to k | C ++ program for the above approach ; Calculate all subarrays ; Calculate required sum ; Check if sum is equal to required sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 10 , 2 , -2 , -20 , 10 } ; int k = -10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( sum == k ) res ++ ; } } cout << ( res ) << endl ; }