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
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?
Answer
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
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 [ ]
No comments:
Post a Comment