×

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

C printf and Scanf

Input-Output functions in C Programming In C Language, the printf() and scanf() are inbuilt library functions that used for input and output. It is defined in the header file“<stdio.h>”. printf() Function: In C...

2 minutes read.

Nested Loops in C Programming Examples

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the...

6 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 minutes read.

C Array

An array is a collection of elements that are used to hold the fixed number of values of the same type. We cannot change the size and type of array...

2 minutes read.

Ftell() Function in C

Ftell(): In File Handling we have some special functions like Ftell(), Fseek(), rewind() etc.. while you are randomly accessing the file these functions play very important role and these functions...

3 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Macros in C

In the C programming language, the macro is defined as a segment of the code replaced by the macro defined value at the beginning. ‘#define’ is the directive that defines...

3 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

Character Class Tests in C

Introduction The <ctype.h> is a header file in C which is used to declare functions for testing characters. This header file of the C standard library is used to declare multiple...

4 minutes read.

String Handling functions in C

String :- The String is the collection of characters. Every String ends with the null character, and the String is enclosed in the double quotations .ie, "javaTpoint". If we see any...

5 minutes read.

Armstrong program in C using function

In this article we will learn how to find Armstrong of a number using function in C. An Armstrong number is a three-digit number that is the sum of its separate...

1 minute read.

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.

Pascal Triangle in C

The pascal triangle in c is an array of binomial coefficients in triangular form. Here the nth row contains the binomial coefficient of ncr.In a pascal triangle, every number is...

2 minutes read.

For loop in C Programming

In the C programming language, the for loop is used to repeatedly iterate over a set of instructions or a section of code. It is frequently used to traverse array-based...

3 minutes read.

Merge and Merge sort with example in C

Assume we have two ordered Integer arrays, a[] and b[]. If we wish to combine them into another ordered array, such as c[], we can use the following straightforward technique. Compare...

3 minutes read.