This is the code I wrote, but instead of showing a total for each line, it shows:
line 1: sum of line 1 (this shows correctly)
line 2: sum of line 1 and line 2
line 3: sum of line 1 thru 3
line 4: sum of line 1 thru 4
line 5: sum of line 1 thru 5
Can someone tell me which part I did it wrong?
#include <stdio.h>
#define YEARS 5
#define MONTHS 12
int main() {
int years;
int months;
int TotalYearlyRainfall = 0;
int rain[YEARS][MONTHS] = {
{1,1,1,1,1,1,1,1,1,1,1,1},
{2,2,2,2,2,2,2,2,2,2,2,2},
{3,3,3,3,3,3,3,3,3,3,3,3},
{4,4,4,4,4,4,4,4,4,4,4,4},
{4,4,4,4,4,4,4,4,4,4,4,4}
};
printf("Total Rainfall\n");
for (years = 0; years < YEARS; years++) {
for (months = 0; months < MONTHS; months++)
TotalYearlyRainfall+=rain[years][months];
printf("%i\n", TotalYearlyRainfall);
}
return 0;
}
years,months, andTotalYearlyRainfallcan be locally scoped to your loops.TotalYearlyRainfallbe changed toMonthlyRainfall, becauseTotalYearlyRainfallis kind of misleading.