How to sum 2dimensional arrays

May 15, 2013 at 1:15pm
I wrote this code in c++ but i m stuck cause i have to sum the 2 arrays i dont know how.Can someone please hep me out??


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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  #include <iostream>
#include <cstdlib>

using namespace std;

int arraySum(int A[5][5],int B[5][5])
{
    int C[5][5];
    for(int i = 0;i<5;i++){
        for(int j = 0;j<5;j++)
        {
            C[i][j]= A[i][j] + B[i][j] ;
        }
    }
    return C[5][5];
}

void printArray(char name,int rows[],int columns[],int elements[])
{
    int A[5][5];
    cout<<name<<'='<<'['<<'{';
    for(int i = 0; i<5;i++)
    {cout<<endl;
        for(int j = 0;j<5;j++)
        {
            if( (i+1)==rows[i] && (j+1)==columns[i])
            {
                A[i][j] = elements[i];
            }
            else
            A[i][j] = 0;
            cout<<A[i][j]<<',';
        }
        cout<<'}';
    }cout<<']'<<endl;

}

int main()
{
   int rowA[]={1,2,3,4,5};
   int rowB[]={1,2,3,4,5};
   int columnA[]={5,4,3,2,1};
   int columnB[]={2,1,3,5,4};
   int elementsA[]={5,10,15,20,25};
   int elementsB[]={30,35,40,45,50};
   printArray('A',rowA,columnA,elementsA);
   printArray('B',rowB,columnB,elementsB);





    system("PAUSE");
    return EXIT_SUCCESS;
}
May 15, 2013 at 2:17pm
It is enough to say that this function

1
2
3
4
5
6
7
8
9
10
11
int arraySum(int A[5][5],int B[5][5])
{
    int C[5][5];
    for(int i = 0;i<5;i++){
        for(int j = 0;j<5;j++)
        {
            C[i][j]= A[i][j] + B[i][j] ;
        }
    }
    return C[5][5];
}


is invalid. You are trying to return element C[5][5] that is absent in the array declared as C[5][5] because valid indexes are in the range 0 - 4. I think that you should declare the function the following way

void arraySum( const int A[][5], const int B[][5], int C[][5], int n );

or

void arraySum( const int ( &A )[5][5], const int ( &B )[5][5], int ( &C )[5][5] );

Last edited on May 15, 2013 at 2:18pm
Topic archived. No new replies allowed.