### multi D array clear buffer?

Learning multi-D arrays. I have this menu program I'm trying to write that is returning some number I'm not expecting for case 3 and I'm not sure why. Do I need to clear a buffer? thoughts?

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697`` ``````const int ROWS = 4; const int COLS = 4; using namespace std; //prototypes int Menu(); int GetTotal(int[][COLS]); double GetAvg(int); int GetRowTotal(int[][COLS],int); int GetColTotal(int[][COLS],int); int GetHighRow(int[][COLS],int); int GetLowRow(int[][COLS],int); int main() { int choice,numtotal,rowchoice,colchoice; int myArray[ROWS][COLS] = {18,48,3,4,12,9,7,32,3,10,4,23,12,115,1,50}; do { choice = Menu(); switch(choice) { case 1: cout << "Total = "; cout << GetTotal(myArray) << endl << endl; break; case 2: cout << "Average = "; numtotal = GetTotal(myArray); cout << GetAvg(numtotal) << endl << endl; break; case 3: cout << "Enter row number: "; cin >> rowchoice; if(rowchoice < 0 || rowchoice >= ROWS) { cout << "Invalid row #. Must be between 0 - "; cout << ROWS << ". Please try again." << endl; break; } else { cout << "Total for Row " << rowchoice << "= "; cout << GetRowTotal(myArray,rowchoice) << endl; break; } } cout << endl; }while (choice != 7); system("PAUSE"); return EXIT_SUCCESS; } int Menu() { int mychoice; cout << "Choose a menu option: " << endl; cout << "1- Total of all numbers\n"; cout << "2- Average of all numbers\n"; cout << "3- Total of a specific row\n"; cout << "4- Total of a specific column\n"; cout << "5- Highest value in a specific row\n"; cout << "6- Lowest value in a specific row\n"; cout << "7- Exit\n\n"; cout << "Enter your choice: "; cin >> mychoice; return mychoice; } int GetTotal(int myArray[][COLS]) { int total = 0; for(int i = 0; i < ROWS; i++) for(int j = 0; j < ROWS; j++) total += myArray[i][j]; return total; } double GetAvg(int totalnum) { double avg; avg = totalnum / (ROWS * COLS); return avg; } int GetRowTotal(int myArray[][COLS],int row) { int rowtotal; for(int i = 0; i < ROWS; i++) rowtotal += myArray[row][i]; return rowtotal; }``````
You forgot to initialize rowtotal in GetRowTotal.
oh duh. thanks Peter87!

But... I'm getting 40, when I'm expecting 60. Shouldn't it read rows left to right? so my 2nd row is {12,9,7,32}, but I'm getting 40. Am I understanding the direction that it reads incorrectly?
Array indices starts at zero so if you input 2 (rowchoice = 2) you will get the sum of the third row.
Last edited on
oh right! thank you again!
Topic archived. No new replies allowed.