Passing 2d arrays to functions

hey guys i need some help plz tell me how do i pass 2d array as parament to a function with user defined dimentions ..

#include<iostream>
using namespace std;

void sum(int [][5],int,int);
int main()
{
int arr[5][5], m,n;
cout<<"Enter size of the sqaure matrix (max 5)"<<endl;
cin>>m>>n;
cout<<"Enter the matrix row wise:"<<endl;
for (int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cin>>arr[i][j];
}
sum(arr,m,n);
}
void sum(int a[][5],int row,int col)
{

for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
if(i==j)
sum=sum+a[i][j];
}
cout<<"The sum of right diagonal is "<<sum<<endl;
}


can someone tell me what's wrong with this one ??
Please use proper code formatting, edit your post and add [code] and [/code] between your C++ code.

sum=sum+a[i][j]; sum is a function. You can't use add to a function as if it's an int or something.

Have a variable name that isn't the same name as your function name, and add to that instead.
Also, don't be afraid to use spaces, they make code much more readable for most people. Of course, different spacing styles are subjective.
1
2
3
4
5
6
7
8
9
10
11
void sum(int a[][5],int row,int col)
{    
    int summ = 0;
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            if (i == j)
                summ = summ + a[i][j]; 
    }
    cout << "The sum of right diagonal is  "<< summ << endl;
}


PS: Your code can be simplified to just one for loop
1
2
3
4
5
6
7
8
9
#include <algorithm> // std::min

/// ...

int summ = 0;
for (int i = 0; i < std::min(row, col); i++)
{
    summ = summ + a[i][i];
}
Last edited on
Thanks bro and ill be carefull next time i didnt knew since im new here.
Topic archived. No new replies allowed.