Subarray with Given Sum
This program finds subarray with a given sum.
Problem Statement
Write a Java program to find a subarray with sum equal to 15.
Source Code
| 1 | public class SubarrayGivenSum { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Subarray Given Sum"); |
| 4 | int[] arr = {1,2,3,7,5}; |
| 5 | int sum=15; |
| 6 | for(int i=0;i<arr.length;i++){ |
| 7 | int currSum=0; |
| 8 | for(int j=i;j<arr.length;j++){ |
| 9 | currSum+=arr[j]; |
| 10 | if(currSum==sum){ |
| 11 | System.out.println("Subarray found from index "+i+" to "+j); |
| 12 | return; |
| 13 | } |
| 14 | } |
| 15 | } |
| 16 | System.out.println("No subarray found"); |
| 17 | } |
| 18 | } |
Program Output
Eduinq Subarray Given Sum Subarray found from index 1 to 3
Explanation
Nested loops check all possible subarrays by extending the ending index and updating a running sum, and when the sum matches the target, the corresponding starting and ending indices are printed, demonstrating a subarray sum search.