I am writing a program for learning purposes that takes an input of a file structured similarly to:
13,22,13,14,31,22, 3, 1,12,10
11, 4,23, 7, 5, 1, 9,33,11,10
40,19,17,23, 2,43,35,21, 4,34
30,25,16,12,11, 9,87,45, 3, 1
1,2,3,4,5,6,7,8,9,10
Which will then read the values from the file, figure out and print the largest sum you can make from the digits on each line which is 50 or less. (Also can not be the same number used twice). I feel I have come to an okay solution but there are a few issues. I want to try and separate the code into separate functions and currently if the text file inputted ends with a newline char the program loops once too far and hence prints out the calculation for a non existent line, I'm not sure how to get around this.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
int hv, lv,line,i, linecount,val[5][10]; //hv + lv = the two highest values on a line, line=sum of hv and lv.
int j=0;
// test file succesfully opened
if((fp=fopen(argv[1], "r")) == NULL){
printf("Cannot open file.\n");
exit(1);
}
//Store values in 2d array
for(i=0;!feof(fp);i++){
while(j<10){
fscanf(fp, "%d,",&val[i][j++]);
}
j=0;
}
linecount=i-1; //set linecoutn to No of lines
//test and print result
for(i=0; i<=linecount; i++){ // for each line
hv=0, lv=0, line=0; //reset values for each line
for(j=0;j<10;j++){ // for each value
for(int a =0; a<10; a++) { //test against all in line
if(a!=j && (val[i][j]+val[i][a]<=50)){ //if two values arent equal and sum is less than 50
if((val[i][j]+val[i][a])>line){ //if value is greater than previous value
hv=val[i][j];
lv=val[i][a];
line=hv+lv;
}
}
}
}
printf("Line %d: largest pair is %d and %d, with a total of %d\n", i+1, hv, lv, line);
}
fclose(fp);
}
So what I'm looking for is code optimization advice and help
Thanks