424,946 Members | 717 Online
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

# I need help with this C program

 P: 5 how to write a program that reads integers until end-of-file and then prints the maximum sum of consecutive values? example: if the input is 27 6 -50 21 -3 14 16 -8 42 33 -21 9 the output is 115 which is the sum of 21 -3 14 16 -8 42 33 Sep 17 '06 #1
5 Replies

 P: 10 you neab it is the sun of: 27 6 -50 21 -3 14 16 -8 42 33 -21 9 Sep 17 '06 #2

 P: 5 you neab it is the sun of: 27 6 -50 21 -3 14 16 -8 42 33 -21 9 the program wants the maximum sum of consecutive values: if i sum all, it would be: 27 + 6 + -50 + 21 -3 + 14 + 16 + -8 + 42 + 33 + -21 + 9 = 86 < 115 Sep 17 '06 #3

 100+ P: 293 Open the file, and read all the integers into an integer array. If you have trouble with that like I do, just google it, there are plenty of examples. Suppose you have N integers. You need two integer arrays of size N. One array is to keep track of the running sum, the other array is to keep track of the maximum. The first entry is for the sum starting with the first number, the second entry is for the sum starting from the second number, etc. Suppose the input is {-1, 2, -3, 4, -5}. The following shows the values of each array after one iteration. Expand|Select|Wrap|Line Numbers    Total Sum               Max Value { 0, 0, 0, 0, 0}       { 0, 0, 0, 0, 0} {-1, 0, 0, 0, 0}       { 0, 0, 0, 0, 0} { 1, 2, 0, 0, 0}       { 0, 2, 0, 0, 0} {-2,-1,-3, 0, 0}       { 0, 2, 0, 0, 0} { 2, 3, 1, 4, 0}       { 0, 3, 1, 4, 0} {-3,-2,-4,-1,-5}       { 0, 3, 1, 4, 0} After those calculations, traverse through the array max value, looking for the maximum. In this case, {0, 3, 1, 4, 0}. After each iteration through the array, the maximum of maxiums will take the values 0, 3, 3, 4, 4. Therefore 4 is the maximum. Sep 17 '06 #4

 P: 5 thanks for the reply. But, I still face difficulty..is there a simpler program? Sep 18 '06 #5

 100+ P: 293 I suppose you could brute force it. Expand|Select|Wrap|Line Numbers // Read all N integers into an array, say int data[N].   int max = 0; int sum; for (int i = 0; i < N; i++) {   sum = 0;   for(int j = i; j < N; j++)   {     sum += data[j];     if(sum > max)       max = sum;   } } Using the same example from before: -1 2 -3 4 -5 sum takes values (I will bold when max is assigned) Expand|Select|Wrap|Line Numbers 0 -1 1 -2 2 -3 0 2 -1 3 -2 0 -3 1 -4 0 4 -1 0 -5 Sep 18 '06 #6