Skip to content

Commit a27b31f

Browse files
authored
Create SubarrayWithGivenSum.cpp
1 parent d687bab commit a27b31f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

C++/SubarrayWithGivenSum.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/* A simple program to print subarray
2+
with sum as given sum */
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
/* Returns true if the there is a subarray
7+
of arr[] with sum equal to 'sum' otherwise
8+
returns false. Also, prints the result */
9+
void subArraySum(int arr[], int n, int sum)
10+
{
11+
12+
// Pick a starting point
13+
for (int i = 0; i < n; i++) {
14+
int currentSum = arr[i];
15+
16+
if (currentSum == sum) {
17+
cout << "Sum found at indexes " << i << endl;
18+
return;
19+
}
20+
else {
21+
// Try all subarrays starting with 'i'
22+
for (int j = i + 1; j < n; j++) {
23+
currentSum += arr[j];
24+
25+
if (currentSum == sum) {
26+
cout << "Sum found between indexes "
27+
<< i << " and " << j << endl;
28+
return;
29+
}
30+
}
31+
}
32+
}
33+
cout << "No subarray found";
34+
return;
35+
}
36+
37+
// Driver Code
38+
int main()
39+
{
40+
int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
41+
int n = sizeof(arr) / sizeof(arr[0]);
42+
int sum = 23;
43+
subArraySum(arr, n, sum);
44+
return 0;
45+
}
46+
47+
// This code is contributed
48+
// by rathbhupendra

0 commit comments

Comments
 (0)