w3resource

C Exercises: Find a subarray with given sum from the given array


47. Subarray with Given Sum

Write a program in C to find a subarray with a given sum from the given array.

The program searches for subarrays within a given array whose elements sum to a specified value. It iterates through the array, calculating the sum of subarrays starting from each index and prints those subarrays that match the desired sum.

Sample Solution:

C Code:

#include <stdio.h>

// Function to print subarrays
void print(int arr1[], int i, int j)
{
    // Print subarray elements within range [i..j]
    printf("[%d..%d] -- { ", i, j);
    for (int k = i; k <= j; k++)
    {
        printf("%d ", arr1[k]);
    }
    printf("}\n");
}

// Function to find subarrays with a given sum
void PickSubarrayFromArray(int arr1[], int n, int sum)
{
    // Loop through each element in the array
    for (int i = 0; i < n; i++)
    {
        int sum_upto = 0;
        // Find subarrays starting from index i
        for (int j = i; j < n; j++)
        {
            sum_upto += arr1[j]; // Increment sum with the element at index j
            if (sum_upto == sum)
            {
                // If the sum matches the target sum, print the subarray
                print(arr1, i, j);
            }
        }
    }
}

int main()
{
    int arr1[] = { 3, 4, -7, 1, 3, 3, 1, -4 };
    int sum = 7;
    int ctr = sizeof(arr1) / sizeof(arr1[0]);
    int i;

    // Print the original array
    printf("The given array is :  ");
    for (i = 0; i < ctr; i++)
    {
        printf("%d  ", arr1[i]);
    }
    printf("\n");

    // Find subarrays with the given sum and print them
    PickSubarrayFromArray(arr1, ctr, sum);
    return 0;
}

Sample Output:

The given array is :  3  4  -7  1  3  3  1  -4  
[0..1] -- { 3 4 }
[0..5] -- { 3 4 -7 1 3 3 }
[3..5] -- { 1 3 3 }
[4..6] -- { 3 3 1 }

Flowchart:

Flowchart: Find a subarray with given sum from the given array.

For more Practice: Solve these Related Problems:

  • Write a C program to find all subarrays with a given sum using nested loops.
  • Write a C program to identify a subarray with a given sum using the sliding window technique.
  • Write a C program to find a subarray with a specified sum using recursion.
  • Write a C program to detect and print all subarrays that add up to a given sum.

Go to:


PREV : Smallest Positive Missing Number (Unsorted Array).
NEXT : Majority Element Occurrence (> n/2).

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.