Subarray with given sum in c++
#include <iostream>
using namespace std;
bool subArraySum(int arr[], int n, int sum) {
int curr_sum = arr[0], start = 0, i;
for (i = 1; i <= n; i++) {
while (curr_sum > sum && start < i - 1) {
curr_sum = curr_sum - arr[start];
start++;
}
if (curr_sum == sum) {
cout << "Sum found between indexes " << start << " and " << i - 1 << endl;
return true;
}
if (i < n) {
curr_sum = curr_sum + arr[i];
}
}
cout << "No subarray found" << endl;
return false;
}
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;
}
Explanation:
Header Files: The program includes necessary header files, such as
<iostream>
, to enable input and output stream operations.Namespace: The
using namespace std;
statement allows the usage of elements in the standard C++ library without prefixing them withstd::
.subArraySum Function: It's a function that takes an array (
arr[]
), its size (n
), and a sum (sum
) to find if there's a subarray with the given sum.curr_sum
initializes with the first element of the array (arr[0]
).start
keeps track of the starting index of the current subarray.- The
for
loop iterates through the array elements from the second element (i = 1
) ton
. - The
while
loop runs as long ascurr_sum
is greater than the givensum
andstart
is less thani - 1
. It helps in adjusting the subarray to find the sum. - If
curr_sum
matches the givensum
, it prints the starting and ending indexes of the subarray and returnstrue
. - If
i
is less thann
, it updatescurr_sum
by adding the current element.
Main Function:
- Declares an array
arr[]
with some values. - Calculates the size of the array (
n
). - Defines the
sum
to find a subarray with this sum. - Calls
subArraySum
function with the given array, its size, and the desired sum.
- Declares an array
Output:
- The function outputs the indexes where the subarray with the given sum is found or outputs "No subarray found" if no such subarray exists.