Q:

C program to find the sum of the largest contiguous subarray

0

C program to find the sum of the largest contiguous subarray

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to split an array and add the first half... >>
<< C program to add two dynamic arrays...