fork(5) download
  1. /* An efficient program to print subarray with sum as given sum */
  2. #include<stdio.h>
  3.  
  4. /* Returns true if the there is a subarray of arr[] with sum equal to 'sum'
  5.   otherwise returns false. Also, prints the result */
  6. int subArraySum(int arr[], int n, int sum)
  7. {
  8. /* Initialize curr_sum as value of first element
  9.   and starting point as 0 */
  10. int curr_sum = arr[0], start = 0, i;
  11.  
  12. /* Add elements one by one to curr_sum and if the curr_sum exceeds the
  13.   sum, then remove starting element */
  14. for (i = 1; i <= n; i++)
  15. {
  16. // If curr_sum exceeds the sum, then remove the starting elements
  17. while (curr_sum > sum && start < i-1)
  18. {
  19. curr_sum = curr_sum - arr[start];
  20. start++;
  21. }
  22.  
  23. // If curr_sum becomes equal to sum, then return true
  24. if (curr_sum == sum)
  25. {
  26. printf ("Sum found between indexes %d and %d", start, i-1);
  27. return 1;
  28. }
  29.  
  30. // Add this element to curr_sum
  31. if (i < n)
  32. curr_sum = curr_sum + arr[i];
  33. }
  34.  
  35. // If we reach here, then no subarray
  36. printf("No subarray found");
  37. return 0;
  38. }
  39.  
  40. // Driver program to test above function
  41. int main()
  42. {
  43. int arr[] = {3, 34, 4, 12, 5, 2};
  44. int n = sizeof(arr)/sizeof(arr[0]);
  45. int sum = 9;
  46. subArraySum(arr, n, sum);
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
No subarray found