Jane
Jane

Reputation: 57

Counting the total of an int array

I have this code:

int sum = 0;
    for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
        for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities) 
            sum = COST[j][j+1]; 
        }
        fitness[i] = sum;
    }  

I am trying to add all the COSTS. Sum is meant to equal the the total of adding all the elements.

The problem I'm facing is that each time the loop runs, sum is set to the next value, as aposed to the total of adding the previous and the current values.


Given people's answers I can now see my rather foolish error. Is this a case of remembered fundamentals before you over complicate?

Upvotes: 0

Views: 57

Answers (3)

Guffa
Guffa

Reputation: 700262

You are assigning each value to the variable, you need to add the value to it. You can use the += operator for that.

To get a sum for each population you need to initialise the variable inside the outer loop:

for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
    int sum = 0;
    for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities) 
        sum += COST[j][j+1]; 
    }
    fitness[i] = sum;
}

Note: I don't know how your data is arranged, but in COST[j][j+1] you are using the variable j for both indexes, it seems like you should use i for one of them.

Upvotes: 1

Kumaresan Perumal
Kumaresan Perumal

Reputation: 1956

you add += this operator to sum the values;

int sum = 0;
    for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
        for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities) 
            sum += COST[j][j+1]; 
        }
        fitness[i] = sum;
    } 

Upvotes: 0

janos
janos

Reputation: 124646

To accumulate the sum, change sum = ... to sum += ...:

sum += COST[j][j+1];

Btw, I don't know your ultimate goal, but I'm wondering if you might also want to move the int sum = 0 inside the outer for loop. Maybe not, it depends on what you're trying to do, this just looks suspicious, that's all, for your consideration.

Upvotes: 1

Related Questions