×

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

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Scope of variables in C

Introduction The scope of variables in C can be defined as the scope of reach of a variable, the term scope is used to determine the visible range of an object....

4 minutes read.

C String Manipulation programs without using Library Functions

C string manipulation programs without using Library Functions The string is the character list, and typically we operate with library functions to read and print the entire string, but here you...

6 minutes read.

Functions in C

What is function? Functions are defined as the set of announcements which take inputs, perform operations and provide results. The operation of a function only performs when the function gets called....

4 minutes read.

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

Addition of Matrix in C

The mathematical operation of includingor greater matrices is called the addition of matrices. A matrix is a square series of numbers, symbols, words, letters, and different things. In this article,...

3 minutes read.

Prototype in C

A prototype is nothing but a model, a model of initial creation of an intended product. Similarly, in the C programming language, all functions have a prototype. In general, all...

4 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

Pre-increment and Post-increment in C

The rich set of operators is supported by the c language. In c there are several operators used. The mathematical operations in the programming language are done with the operators...

4 minutes read.

Array to function in C

Array to function in C We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the...

4 minutes read.

Infinite loop in C

Definition of infinite loop The infinite loop is a loop that does not get dismissed because of its looping construct. A continuous output or no output are the two possible outcomes...

3 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

While Loop in C programming examples

Introduction There is always a header file containing all the essential data regarding inputs and outputs of various functions in the C programs. The following statement describes how to use/add header file...

22 minutes read.

Dos.h Header File in C Language

Dos.h is a header file in C. Interrupt handling, sound generation, date and time functions, and other tasks can be performed using the functions in this library. This is exclusive to...

4 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.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

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.