| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
2-D array addition
Could someone give me a bit of advice on how to add the contents of a 2D array? I am working from a book and one of the exercises ask you to enter book sales for a 3 year period. Then it aska you to calculate the total for each year then the total for all the years. I can get the total for all the years but for the life of me i can't get the total for each individual year. I do a nested loop but it keeps adding all the arrays. I will put the code here:
// 2D_array_for_3_years.cpp -- storing 3 years of book sales in a 2D array #include <iostream> const int YEARS = 3; const int MONTHS = 12; int books[YEARS][MONTHS]; using std::cout; using std::cin; using std::endl; int main(void) { cout << "Enter each monthly value of books for a 3 year period.\n\n"; int individual = 0; int combined = 0; int year, month; for ( year = 1; year <= YEARS; year++ ) { cout << "Year #" << year << ": " << endl; for ( month = 0; month < MONTHS; month++ ) cin >> books[year][month]; cout << endl; } // output each individual years total for ( year = 0; year <= YEARS; year++ ) for ( month = 0; month < MONTHS; month++ ) combined += books[year][month]; cout << "The combined total for all three years is: " << char ( -100 ); cout << combined; return 0; } i just want someone to point me in the right direction if at all possible. Thanks in advance Paul820 |
|
#2
|
|||
|
|||
|
I don't see any code that attempts to total individual years. but the pseudocode would be:
Code:
iterate through years
total = 0
iterate through months
total += current
end iterating through months
output total
end iterating through years
|
|
#3
|
|||
|
|||
|
Thank you
Thanks a lot ubergeek, i have been banging my head for about 3 hours trying to get it to work. You're right the code wasn't there because it ended up doing the same as the total for all the years. I just posted the code so people would get a better understanding of what i wanted.
Anyway, followed your advice : // output each individual years total int y, m; for ( y = 1; y <= YEARS; y++ ) { int individual = 0; for ( m = 0; m < MONTHS; m++ ) individual += books[y][m]; cout << "Year #" << y << " : "; cout << individual << endl; The way i was doing it, it was cycling through the whole lot. Thanks for the really fast reply, appreciate that. Paul820 |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > 2-D array addition |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|