×

Find a subarray with a given sum.

Find a subarray with a given sum.

The simple solution is to recognize all subarrays one by one and to check each subarray's sum. The quick solution follows the following program.

Algorithm:

  • From beginning to end, traverse the array.
  • For each index in the internal loop update number = sum + array[s]
  • If the sum is equal to the sum given, then the subarray is printed out.
/* A simple program to print 
subarray with sum as given sum */
#include <stdio.h>
int subArraySum(int arr[], int p, int sum)
{
    int curr_sum, k, s;
    // Pick a starting point
    for (k = 0; k < p; k++) {
        curr_sum = arr[k];
        // try all subarrays starting with 's'
        for (s = k + 1; s <= p; s++) {
            if (curr_sum == sum) {
                printf(
                    "Sum found between indexes %d and %d",
                    k, s - 1);
                return 1;
            }
            if (curr_sum > sum || s == p)
                break;
            curr_sum = curr_sum + arr[s];
        }
    }
    printf("No subarray found");
    return 0;
}
// Driver program to test above function
int main()
{
    int arr[] = { 15, 4, 8, 16, 18, 10, 20, 43 };
    int p = sizeof(arr) / sizeof(arr[0]);
    int sum = 43;
    subArraySum(arr, p, sum);
    return 0;
}

Output:

Find a subarray with a given sum.

Effective approach: If all of the elements in the collection are positive, then there is a concept. There is no probability that adding elements to the current subarray would be x (given sum) if a subarray has a number greater than the given sum. The aim is to use an approach similar to a sliding window. Start by adding elements to the subarray with an empty subarray until the sum is less than x. If the sum is higher than x, delete elements from the current subarray startup.

Algorithm:

Construct three variables, s=0, sum = 0

From beginning to end traverse the array.

Change the variable sum by adding current element, sum = sum + array[s]

Change the value of the variable as value = sum-array[s], and update s as, s++ if the sum is larger than the sum.

/* An efficient program to print 
subarray with sum as given sum */
#include <stdio.h>
int subArraySum(int arr[], int t, int sum)
{
    /* Initialize curr_sum as 
       value of first element and 
starting point as 0 */
    int curr_sum = arr[0], start = 0, m;
    /* Add elements one by one to 
curr_sum and if the curr_sum 
       exceeds the sum, then remove 
starting element */
    for (m = 1; m <= t; m++) {
        // If curr_sum exceeds the sum,
        // then remove the starting elements
        while (curr_sum > sum && start < m - 1) {
            curr_sum = curr_sum - arr[start];
            start++;
        }
        // If curr_sum becomes equal to sum,
        // then return true
        if (curr_sum == sum) {
            printf(
                "Sum found between indexes %d and %d",
                start, m - 1);
            return 1;
        }
        // Add this element to curr_sum
        if (m < t)
            curr_sum = curr_sum + arr[m];
    }
    // If we reach here, then no subarray
    printf("No subarray found");
    return 0;
}
// Driver program to test above function
int main()
{
    int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
    int t = sizeof(arr) / sizeof(arr[0]);
    int sum = 23;
    subArraySum(arr, t, sum);
    return 0;
}

Output:

Find a subarray with a given sum.

Related Topics

Evaluation of Arithmetic Expression in C

We can use the "eval" function in C to evaluate an arithmetic expression stored as a string. However, using "eval" is generally considered bad practice and can lead to security...

4 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

C Switch Statements

Switch-case statement comes under the Selection control statement; there are four types of Control statements Decision-making statements (if, if-else)Selection statements (Switch-case)Iteration statements (for, while, do-while)Jump statements (break, continue, goto) If we want...

4 minutes read.

What is Linked List in C

Linked list Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory...

7 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

Isalnum() function in C

Introduction: The isalnum () is a function used in C programming language. This function checks the passing number or argument is an alphanumeric number or not. The alphanumeric number consists of the...

3 minutes read.

Explain the two-way selection in C

In C programming, a two-way selection statement is used to choose between two different options based on a Boolean expression. The two-way selection statement in C is the if statement. The...

6 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Commenting in C

Commenting in C Commenting in the C language is used to give out the information about the lines of the code which are included. It is one of the things that...

3 minutes read.

Reverse a Stack using Recursion in C

In this tutorial we will learn how recursion will be used in this case to reverse a stack. For loops, while loops, do-while loops, and similar constructions are not permitted....

5 minutes read.

C Program of Fencing the Ground

The college's ground is rectangular. Fencing the ground the management makes the decision to construct a fence around the ground. They planned to wrap a thick rope around the ground...

1 minute read.

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling...

4 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Calloc in C

The calloc() is a library function in C which is used for memory allocation. The calloc() function dynamically allocates multiple blocks of memory to complex data structures. This includes data structures...

3 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.