From 8a36b89e62a0d1b7df39ba8646f028c483cac5ce Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:41:22 +0530 Subject: [PATCH] Create Find Subarray with given sum --- Find Subarray with given sum | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Find Subarray with given sum diff --git a/Find Subarray with given sum b/Find Subarray with given sum new file mode 100644 index 0000000..cddee7d --- /dev/null +++ b/Find Subarray with given sum @@ -0,0 +1,48 @@ +/* A simple program to print subarray +with sum as given sum */ +#include +using namespace std; + +/* Returns true if the there is a subarray +of arr[] with sum equal to 'sum' otherwise +returns false. Also, prints the result */ +void subArraySum(int arr[], int n, int sum) +{ + + // Pick a starting point + for (int i = 0; i < n; i++) { + int currentSum = arr[i]; + + if (currentSum == sum) { + cout << "Sum found at indexes " << i << endl; + return; + } + else { + // Try all subarrays starting with 'i' + for (int j = i + 1; j < n; j++) { + currentSum += arr[j]; + + if (currentSum == sum) { + cout << "Sum found between indexes " + << i << " and " << j << endl; + return; + } + } + } + } + cout << "No subarray found"; + return; +} + +// Driver Code +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; +} + +// This code is contributed +// by rathbhupendra