Question:
programming c subvectors?
ur boy needo
2007-10-30 13:36:11 UTC
i am using C and i need help with subvectors, i have to make a program that does the following

A file contains a list of integers. The integers can, and are likely to, contain a mix of positive and negative values. The name of the file comes into your program via argv[1].
The first n numbers of the file are read by your program. The number n comes into your program via argv[2]. The number n will be no greater than 200,000.

For example, the file could contain the values:

-3 100 -4 -2 9 –63 -200 55

Your program will output a number that is the largest sum found in a subvector of this list. In the example above, the output would be 103 since that is the largest sum that can be formed by adding the elements of any subvector.

A subvector can be the entire list, a single member of the list, or it can be any collection of adjacent numbers. If the entire list of numbers contains negative numbers then your program should output 0.

Here is another example: 1 4 3 -4 8
The answer in this case would be 12 since the entire list of numbers forms the maximum sum.
Three answers:
SWEngr
2007-10-30 14:19:21 UTC
#include /* Include lots of standard definitions */

#include /* Get more useful definitions, like atof() */



main(argc,argv) /* Operating System supplies argc & argv */

int argc; /* The number of words in command line */

char *argv[]; /* The sequence of words in command line */

{ /* argv[0] is the program name */

int i; /* a loop counter - always an integer */

int highest; /* Highest number*/

int high2nd; /* 2nd highest*/

int temp;

double x, sum; /* working variables, double precision here */

sum = 0; /* Initialize sum to 0 */





for( i = 1 ; i < argc ; ++i ) { /* loop over args[1,...] */

x = atof(argv[i]); /* convert a string to a number */

if(x>high1st) {

temp=highest;

highest = x;

x = temp;

}

if(x>high2nd) {

high2nd=x;

}



}

sum = highest+high2nd;

printf("SUM:%i\n",sum); /* print sum after the loop completes */

}
jochim
2016-10-03 05:04:19 UTC
no longer anymore, at one time C++ replaced into in simple terms an extension of C. when you consider that then, C has replaced, and so has C++. besides the undeniable fact that that being reported it is commonplace for the comparable software to collect the two C and C++. the tactic is the comparable, yet there are in basic terms some adjustments int he libraries which you desire the compiler to link to.
Thejane T
2007-10-30 13:57:24 UTC
You know, the problem here is that us real programmers, although we love writing code, couldn't be bothered to write programs to solve such trivial problems.



Which aspect of the question are you having a problem with? Arrays ("subvectors") can be a bit weird in C sometimes.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...