Matrix

Apr 19, 2011 at 10:52pm
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
5
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


Heres what I have so far but Im getting errors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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;
}
Apr 19, 2011 at 11:05pm
Post the errors.
Apr 20, 2011 at 12:08am
I cant post them right now, since I dont have the compiler program on my laptop.

Anyone else who could help?
Apr 20, 2011 at 12:22am
It compiles fine with g++ -pedantic, although that program doesn't quite do what it's supposed to.

-Albatross
Apr 22, 2011 at 2:38am
Wish I could help ya dude but Im new at all this stuff too!

Is there anyway any of you could post the answer for this guy? Seems pretty lost.

Apr 22, 2011 at 2:55am
The sum function shouldn't be trying to take a constant, because we want to input a normal matrix, not a constant matrix.

EDIT: Sorry, that's wrong, read my next post.
Last edited on May 7, 2011 at 10:58pm
Apr 22, 2011 at 7:25pm
hi here i hav designed it for any general matrix hope it helps......

#include<iostream.h>
void main()
{
int a[4][4],i,j,s=0;
cout<<"Enter the elements of the matrix"<<endl;
for(i=0; i<4; i++)
for(j=0; j<4; j++)
cin>>a[i][j];

cout<<"The sum of the elements of the matrix=";
for(i=0; i<4; i++)
for(j=0; j<4; j++)
s=s+a[i][j];
cout<<s;

}
Apr 23, 2011 at 8:43pm
@suppy: main() must return an int, use iostream not iostream.h, and please don't post full solutions.
May 6, 2011 at 5:47pm
@BROWNI3141: OK I WILL NT POST FULL SOLUTIONS FROM NXT TIME
BT WONT MAIN RETURN AN INT VALUE EVEN THOUGH V HAV NT MENTIONED IT??
May 6, 2011 at 5:54pm
The return(0); at the end is implicit if not explicit, but you still must define main as int main() and not void main(). By the way, I think you hit caps lock by mistake.
May 7, 2011 at 10:57pm
Whoops, discredit that about the constness, you're not changing the matrix so const is fine for the parameter.
Topic archived. No new replies allowed.