0

I am required to create a function which calculates the sum of elements on the diagonal of the matrix with signature int diagonal(int array[4][4])

Here's what I've tried:

int diagonal(int array[4][4]){
    int sum = 0;

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4; j++){
            if (i == j){
            sum = sum + array[i,j];
            }
        }
    }
return sum;
}



#include <iostream>

extern int diagonal(int[][]);
int main (){
    int array[4][4] = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
    std::cout << "The sum is: " << diagonal(array) << std::endl;    
    return 0;
}

Yet it produces some error messages which I don't seem to understand why those are the case:

main-1-1.cpp:3:27: error: multidimensional array must have bounds for all dimensions except the first
 extern int diagonal(int[][]);
                           ^
main-1-1.cpp: In function ‘int main()’:
main-1-1.cpp:6:47: error: too many arguments to function ‘int diagonal()’
  std::cout << "The sum is: " << diagonal(array) << std::endl; 
                                               ^
main-1-1.cpp:3:12: note: declared here
 extern int diagonal(int[][]);
            ^
function-1-1.cpp: In function ‘int diagonal(int (*)[4])’:
function-1-1.cpp:8:14: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
    sum = sum + array[i,j];

Can someone please explain to me regarding that?

user672518
  • 75
  • 9

2 Answers2

2

the answer to this is here Passing a 2D array to a C++ function

try this way instead its a little simpler

#include <iostream>
int diagonal(int array[][4])
{
    int sum = 0;
    for(int I = 0; I < 4; I++)
    {
        sum += array[I][I];
    }
    return sum;
}

int main()
{
    int array[4][4] = {{1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}};
    std::cout << "sum is " << diagonal(array) << std::endl;
    return 0;
}
Henri
  • 145
  • 13
  • This sounds so bad, but if this answers your question, could you please mark this as the answer and upvote me? I'm trying to build reputation for bounties – Henri Aug 03 '19 at 03:45
1
int diagonal(int array[][4]){
    int sum = 0;

    for (int i = 0; i < 4; i++){
        for (int j = 0 ; j < 4; j++){
            if (i == j){
            sum = sum + array[i][j];
            }
        }
    }
return sum;
}



#include <iostream>

extern int diagonal(int[][4]);
int main (){
    int array[4][4] = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
    std::cout << "The sum is: " << diagonal(array) << std::endl;    
    return 0;
}

you can put any number in the first [ ] but the compiler will ignore it. When passing a vector as parameter you must specify all dimensions but the first one. in short, you don't need to pass a value in a function declaration for the first [ ]