text: Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | A simple program to print subarray with sum as given sum ; Returns true if the there is a subarray of arr [ ] with a sum equal to ' sum ' otherwise returns false . Also , prints the result ; Pick a starting point ; try all subarrays starting with ' i ' ; Driver program to test above function
code: #include <stdio.h> NEW_LINE int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum , i , j ; for ( i = 0 ; i < n ; i ++ ) { curr_sum = arr [ i ] ; for ( j = i + 1 ; j <= n ; j ++ ) { if ( curr_sum == sum ) { printf ( " Sum ▁ found ▁ between ▁ indexes ▁ % d ▁ and ▁ % d " , i , j - 1 ) ; return 1 ; } if ( curr_sum > sum j == n ) break ; curr_sum = curr_sum + arr [ j ] ; } } printf ( " No ▁ subarray ▁ found " ) ; return 0 ; } int main ( ) { int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 23 ; subArraySum ( arr , n , sum ) ; return 0 ; }