# Minimum sum of numbers

The code reads an input with numbers and find the sum with the minimum difference of the first two big numbers. The sums are three.

Is there is any way to make the code cleaner? (Note that I don't need to take any restrictions such as NULL parameters, etc)

Moreover, there is an int in my program pA = -1 with that value. Now, because the pA used as pointer you see below that I have the statement ProfitA = array[pA];, that statement doesn't give any problems, but I just wanted to point it out in case you could clean my code a bit.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define TRUE 1
#define FALSE 0
#define min(ProfitA, ProfitB, ProfitC) ProfitA > (ProfitB > ProfitC ? ProfitB : ProfitC) ? ProfitA : (ProfitB > ProfitC ? ProfitB : ProfitC)

int main() {

FILE* input = fopen("share.in","r");
int bestMin = INT_MAX;
int N = 0;
fscanf(input,"%d",&N);

int *array = malloc(N * sizeof(int));

int pA = -1, pB = N - 1;
int ProfitA = 0, ProfitC = 0, ProfitB = 0;

for (int i = 0; i < N; i++) {
fscanf(input,"%d",&array[i]);
ProfitB += array[i];

}

ProfitB = ProfitB - array[pA] - array[pB];
ProfitA = array[pA];
ProfitC = array[pB];

fclose(input);

short flag = TRUE;
int check_L = 0, check_R = 0;

while ((pB - pA != 1) && (flag == TRUE)) {
flag = FALSE;

check_L += ProfitA + array[pA + 1];
check_R += ProfitC + array[pB - 1];

if (check_L < check_R) {

ProfitA = check_L;
ProfitB -= array[pA + 1];
pA++;
flag = TRUE;

}
else {

ProfitC = check_R;
ProfitB -= array[pB - 1];
pB--;
flag = TRUE;
}
check_R = 0, check_L = 0;

printf("k1 = %d, k3 = %d, k2 = %d\n",ProfitA,ProfitB,ProfitC);

int  currentMin = min(ProfitA, ProfitB, ProfitC);

if (currentMin < bestMin) {
bestMin = currentMin;
}

}
printf("%d\n",bestMin);

return 0;
}

• How come pA = -1 is not a problem when accessing an array using that as index ? – Loufylouf Feb 24 '15 at 19:13
• i know it's a very bad problem in general (the array index start from 0) but in my case it works. If there is any way to kick it from my code then that's why I asked here ;) . – Nikos KLon Feb 24 '15 at 19:15
• Please do not modify the original code based on answers. – Jamal Feb 24 '15 at 19:22
• @Jamal ok I'll keep it in mind! – Nikos KLon Feb 24 '15 at 19:24

You definitely can make your code cleaner :

• Your function main does all the job, that's usually quite bad. You can, at least, separate two aspects : reading the input (and store it in an array) and processing the input. That would be a little bit easier to read