tags:

views:

87

answers:

1

Hello I had recently asked a question about how to do the following:

Write a function that sums all the integers in a matrix of integers using the following header:

const int SIZE = 4;
double sumMatrix (const double m [] [SIZE] , int rowSize, int columnSize) ; 

Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements. Heres a sample run:

Enter a 4by4 matrix row by row:

1 2 3 4 [Enter]
5 6 7 8 [Enter]
9 10 11 12 [Enter]
13 14 15 16 [Enter]
Sum of the matrix is 136

I tried to use all the suggestions I could but the problem maybe that I just need to go back to the basic and learn some basic things I have skipped over, but heres what I have so far. Corrections and solutions, and help in any form would be highly appreciated.

#include <iostream>
using namespace std;

const int COLUMN_SIZE = 4;

int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
    int total = 0;
    for (int row = 0; row < rowSize; row++)
    {
        for (int column = 0; column < COLUMN_SIZE; column++)
        {
            total += a[row][column];
        }
    }

    return total;
}
int main()
{
    int m[4][4]=
    {
        {1,2,3,4},
        {5,6,7,8},
        {9,10,11,12},
        {13,14,15,16}
    };
    cout<< "Sum of the matrix"<< sum(m,4) << endl;
    return 0;
}
A: 

The read function that you need will look almost the same as your print function:

void read(const int a[] [COLUMN_SIZE], int rowSize)
{
    for (int row = 0; row < rowSize; row++)
    {
        for (int column = 0; column < COLUMN_SIZE; column++)
        {
            cout << "Enter number for [" << row << "][" << column << "]: ";
            cin >> a[row][column];
        }
    }
}

(As a footnote: if you can generalise the looping and have one function that you pass 'read' or 'sum' to you're well on your way to being awesome)

edit: guess I didn't read the 'row by row' bit of the question. shrug.

Daniel