This is a C Program to find the sum of contiguous subarray within a 1 – D array of numbers which has the largest sum.

This C Program finds the sum of contiguous subarray within a 1 – D array of numbers which has the largest sum.

Prints the sum of contiguous subarray within a 1 – d array of numbers and the largest sum.

Here is source code of the C Program to find the sum of contiguous subarray within a 1 – D array of numbers which has the largest sum. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C Program to Find the Sum of Contiguous Subarray within a 1 - D Array of Numbers which has the Largest Sum */ #include <stdio.h> #include <stdlib.h> int maxSubArraySum(int a[], int size, int *begin, int *end) { int max_so_far = 0, max_end = 0; int i, current_index = 0; for (i = 0; i < size; i++) { max_end = max_end + a[i]; if (max_end <= 0) { max_end = 0; current_index = i + 1; } else if (max_so_far < max_end) { max_so_far = max_end; *begin = current_index; *end = i; } } return max_so_far; } int main() { int arr[] = {10, -2, 15, 9, -8, 12, 20, -5}; int start = 0, end = 0; int size = sizeof(arr) / sizeof(arr[0]); printf(" The max sum is %d", maxSubArraySum(arr, size, &start, &end)); printf(" The begin and End are %d & %d", start, end); getchar(); return 0; }

In this C Program, compute the division of the present array value with next array. In maxSubArraySum()function is used to find the sum of contiguous sub array. Initialize the value of ‘i’ variable as 0 and check the condition that the value of ‘i’ variable is less than the value of ‘size’ variable. Compute the summation of the value of ‘max_end’ variable with the value of a[] array variable and assign to max_end variable.

Nested if else condition statement is used to check that the value of ‘max_end’ variable is less than or equal to 0. If the condition is true, then execute if condition statement. Initialize the value of ‘max_end’ variable as 0 and compute the summation of the value of ‘i’ variable with 1 and assign the value to ‘current_index’ variable.

Otherwise, if the condition is false, then execute the elseif condition statement and check the codition that the value of ‘max_so_far’ variable is less than the value of ‘max_end’ variable. If the condition is true then execute the statement and assign the value of ‘max_end’ variable to ‘max_so_far’ variable.

Assign the value of ‘current_index’ and the value of ‘i’ variable to ‘begin’ and ‘end’ pointer variables respectively.

$ cc pgm89.c $ a.out The max sum is 56 The begin and End are 0 & 6

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms