How do I output a 2D array from a function?

I've declared a double matrix that has several rows and several columns.

I am able to input values accordingly.

When I call the function, it returns only the sum of values in the first column.

I am working in a c++ book that illustrates how to output the values of the array and sum the columns of each array. I can get the right output when I put the code of the function into main. But if I put the code back into the function it just returns the first column's sum of numbers....

I rather not display the code. Hopefully someone can help me understand how a 2D array can be evaluated within a function.

Poast code! It helps us analyze what you're trying to do much better than text. :3
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
        const int r = 3;
	const int c = 4;
	double m[r][c];

	cout << "Enter a 3-by-4 matrix: " << endl;
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			cin >> m[i][j];

}


This is what I have so far in main......I know that the program is storing the input because I can output m[i][j] in for loop. But what I do not know how to do is send the whole 2D matrix to the function. I have tried to call the function like the following: sum(m, 3, 4) and in return it only processes the sum for the first column only. How do I get the function to return each column's sum properly to output?
So you want the total of each column? Which means you're going to have to total each
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//when passing a multidimensional matrix, you must specify the dimensions past the first.
//I recommend using some global constant or define to do this to prevent magic numbers.
void sum(double matrix[][4], int rows, int cols)
{
    //for each column
    for( int c = 0; c < cols; ++c)
    {
        int col_sum = 0;

        //add up each element in that column
        for(int r = 0; r < rows; ++r)
            col_sum += matrix[r][c];

        //output after each column has been totaled 
        cout << col_sum << endl;
    }
}
I have a similar function, its not void though and it returns a value. Thank You for your input.

Even with my function setup like yours, it still just returns the sum for column 0........

Maybe I am not calling the function correctly....I dunno...
Post function! I think what you might be doing is placing the return value inside the second for-loop of the function, which means the function will return immediately. So it will only return one value which is probably why you're only getting the sum of column 0.
If I place "return value;" outside the second for loop, IDE tells me that value is undefined. For summing the columns of the matrix, it shows in the book how to setup the code and it shows specifically how to output the matrix without calling a function, just writing the code as part of main. I think you're on to something....Let me try a couple of things.
Topic archived. No new replies allowed.