// 2D_Array_Operations_N.cpp : Defines the entry point for the console application. // This program belongs to Nichole Moore. #include "stdafx.h" #include <iostream> using namespace std; // Global constants. const int ROWS = 3; const int COLS = 3; // Function prototype. int show1(const int[ROWS][COLS]); int show2(const int[ROWS][COLS], int total); int show3(const int[][COLS], int row[]); int show4(const int[ROWS][COLS]); int main() { int arr[ROWS][COLS] = {{5, 10, 15}, {20, 25, 30}, {35, 40, 45}}; int row[ROWS]; int r, c, total, average, rowTotal, colTotal; // Function call. total = show1(arr); average = show2(arr, total); rowTotal = show3(arr, row); colTotal = show4(arr); // Display. cout << "Total of all values in the array is " << total << "." << endl; cout << "Average is " << average << "." << endl; // Display row total table. cout << "Total of rows is " << endl; for (r = 0; r < ROWS; r++) { cout << row[ROWS]; } return 0; } // Function header. // Total of the numbers in the array. int show1(const int arr[ROWS][COLS]) { int r, c, total = 0; // Total of numbers in 2D Array. for (r = 0; r < ROWS; r++) { for (c = 0; c < COLS; c++) total += arr[r][c]; } return total; } // Average. int show2(const int arr[ROWS][COLS], int total) { int r, c, average = 0; for (r = 0; r < ROWS; r++) { for (c = 0; c < COLS; c++) average = total / 9; } return average; } // Row Total. int show3(const int arr[][COLS], int row[]) // Make the second integer a subscript of the array to choose which row you want totaled? { int r, c, rowTotal; for (r = 0; r < ROWS; r++) { row[ROWS] = 0; // Sum of last row. for (c = 0; c < COLS; c++) row[ROWS] += arr[r][c]; } return row[ROWS]; } // Column Total. int show4(const int arr[ROWS][COLS]) { int r, c, colTotal; colTotal = 0; for (c = 0; c << COLS; c++) { // Sum of last column. for (r = 0; r < ROWS; r++) colTotal += arr[r][c]; } return colTotal; }
The problems I am having with this code so far are the following:
1) My total for rows is only ever displaying the total for the last row and I am trying to figure out how to get it to show either the totals for each row individually, or for a specified row. No matter what I have done so far, it still shows me only the total for the third row.
and
2) I am sure I am going to have the same problem with the column total. I had it written out okay earlier to see if it would do the same thing (total only the last column) but when I ran it, the program needs to be aborted because it is sayd "colTotal" is not initialized when I had it initialized to "0" in the first for loop. But it won't take ANY initialization unless it is outside of both of the for loops (within its own function). But when I do this, the output just comes out as "0." Yet, my compiler does not tell me to do this with "rowTotal."
Please help. I am getting very frustrated with this, lol...
Any help is very much appreciated.