fork(4) download
  1. #include<stdio.h>
  2.  
  3. int subArraySum(int a[], int n, int sum)
  4. {
  5. int i, s_index=0, curr_sum=a[0];
  6. for(i=1; i<n; i++)
  7. {
  8. if(curr_sum==sum)
  9. {
  10. printf("starting and ending index are: %d %d", s_index, i-1);
  11. return 1;
  12. }
  13. else if(curr_sum<sum)
  14. curr_sum=curr_sum+a[i];
  15. else
  16. {
  17. curr_sum=curr_sum-a[s_index];
  18. s_index=s_index+1;
  19. if(curr_sum==sum) //tricky step -> after subtracting check if this new curr_sum==sum or not
  20. {
  21. printf("starting and ending index are: %d %d", s_index, i-1);
  22. return 1;
  23. }
  24. curr_sum=curr_sum+a[i];
  25. }
  26. }
  27. printf("No sub-array found");
  28. }
  29.  
  30. int main()
  31. {
  32. int arr[]={1, 4, 0, 0, 3, 10, 5};
  33. int n = sizeof(arr)/sizeof(arr[0]);
  34. int sum = 7;
  35. subArraySum(arr, n, sum);
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 2252KB
stdin
Standard input is empty
stdout
starting and ending index are: 1 4