×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find the sum of the largest contiguous subarray

Here, we are going to learn how to find the sum of the largest contiguous subarray in C programming language?
Submitted by Nidhi, on July 10, 2021

Program statement

Here, we will create an integer array then find the sum of the largest contiguous subarray and print the result on the console screen.

C - Find the sum of the largest contiguous subarray

The source code to find the sum of the largest contiguous subarray is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

C program to find the sum of the largest contiguous subarray

// C program to find the sum of largest contiguous subarray

#include <stdio.h>

int main()
{
    int i = 0, j = 0, t1 = 0, t2 = 0;
    int large = 0;
    int arr[7];

    printf("Enter the  elements of the array: ");

    for (int i = 0; i < 7; i++)
        scanf("%d", &arr[i]);

    large = arr[0];

    for (i = 0; i < 7; i++) {
        int sum = 0;
        for (int j = i; j < 7; j++) {
            sum = sum + arr[j];

            if (sum > large) {
                t1 = i;
                t2 = j;

                large = sum;
            }
        }
    }

    printf("The largest contiguous subarray: ");
    for (i = t1; i <= t2; i++)
        printf(" %d ", arr[i]);

    printf("\nThe sum of the largest contiguous subarray: %d\n", large);

    return 0;
}

Output

Enter the  elements of the array: -1 0 4 -2 7 -5 2      
The largest contiguous subarray:  0  4  -2  7 
The sum of the largest contiguous subarray: 9

Explanation

Here, we created an array of 7 integer elements then we found the largest contiguous subarray and its sum. After that, we printed the result on the console screen.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.