Since you are summing the final year's population, which is computed in the inner loop, then the summation equation that you need to compute the average should be after the inner loop, but within the outer loop (since you want to include the population of each country).