By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,946 Members | 717 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
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
D_C
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
  1.    Total Sum               Max Value
  2. { 0, 0, 0, 0, 0}       { 0, 0, 0, 0, 0}
  3. {-1, 0, 0, 0, 0}       { 0, 0, 0, 0, 0}
  4. { 1, 2, 0, 0, 0}       { 0, 2, 0, 0, 0}
  5. {-2,-1,-3, 0, 0}       { 0, 2, 0, 0, 0}
  6. { 2, 3, 1, 4, 0}       { 0, 3, 1, 4, 0}
  7. {-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
D_C
I suppose you could brute force it.
Expand|Select|Wrap|Line Numbers
  1. // Read all N integers into an array, say int data[N].
  2.  
  3. int max = 0;
  4. int sum;
  5. for (int i = 0; i < N; i++)
  6. {
  7.   sum = 0;
  8.   for(int j = i; j < N; j++)
  9.   {
  10.     sum += data[j];
  11.     if(sum > max)
  12.       max = sum;
  13.   }
  14. }
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
  1. 0 -1 1 -2 2 -3
  2. 0 2 -1 3 -2
  3. 0 -3 1 -4
  4. 4 -1
  5. 0 -5
Sep 18 '06 #6

Post your reply

Sign in to post your reply or Sign up for a free account.