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:

  1. Header Files: The program includes necessary header files, such as <iostream>, to enable input and output stream operations.

  2. Namespace: The using namespace std; statement allows the usage of elements in the standard C++ library without prefixing them with std::.

  3. 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) to n.
    • The while loop runs as long as curr_sum is greater than the given sum and start is less than i - 1. It helps in adjusting the subarray to find the sum.
    • If curr_sum matches the given sum, it prints the starting and ending indexes of the subarray and returns true.
    • If i is less than n, it updates curr_sum by adding the current element.
  4. 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.
  5. 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.