Calculation of the sum of the elements of a matrix

Asked

Viewed 255 times

-2

I have to develop a function in the C language to sum the elements of a square matrix of order n since i < j. I tried to test the function I did, but it gives error in line 15, which says "expected Expression before 'int'". Could someone help me, please?

#include <stdio.h>
#include <stdlib.h>

int soma_matriz(int n, int mat[n][n]){
    int i = 0, j = 0, soma = 0;
    for (i = 0; i < n; i++){
        for (j = 0; (j < n); j++){
            if (i < j)
                soma = soma + mat[i][j];
        }
    }
    return soma;
}

int main(){
    int mat[3][3] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, a = 3, somatorio = 0;
    somatorio = soma_matriz(int a, int mat[3][3]);
    printf("O valor e %d", somatorio);
    return 0;
}

1 answer

5


There are syntax errors there, for example calling the function with declaration syntax and trying to pass the type as argument, it does not exist, it includes passing the size of the array, you pass a value, which can be of a variable, only that. Also you were not initiating the array the right way. I improved a few more things.

#include <stdio.h>

int soma_matriz(int n, int mat[n][n]) {
    int soma = 0;
    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i < j) soma += mat[i][j];
    return soma;
}

int main() {
    int mat[3][3] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
    printf("O valor e %d", soma_matriz(3, mat));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You need to understand what each part of the text means, because it’s there. Without understanding what you’re doing, just copying things hoping it works will only hit by coincidence, and you won’t learn. The goal cannot be to do the exercise but to understand what is happening so you need to study each concept before doing it. I say this because here we help people learn to program and not just say what she missed punctually, which doesn’t teach much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.