0

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?

1
  • a) use += and not =. b) It would be helpful for your future questions (one that aren't caused by simple typos like this one) to post how you get your data (in this case COST and POPULATION_SIZE) Commented Nov 1, 2015 at 12:09

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.