How does the diagonal sum printf of a matrix

Asked

Viewed 37 times

0

I’m having a hard time creating a printf that depends on the input. I want you to print depending on how many numbers you have diagonally in a matrix and display those numbers. EXAMPLE:

You must print the values used for the calculation of the trace and the value of the trace itself according to the following model:

 tr(A) = (1.00) + (5.00) + (9.00) = 15.00 

IN THE CASE THIS IS A 3X3 MATRIX, BUT IT WILL NOT ALWAYS BE

That’s what I’ve done so far:

#include <stdio.h>


int main() {
int n=0, soma=0, total=0;

scanf("%d", &n);

int matriz[n][n];
for(int i=0; i<n; i++){
  for(int j=0; j<n; j++){
  
    scanf("%d", &matriz[i][j]);
    if(i==j){
    total=total+matriz[i][j];
    
    printf("tr(A) = (%d) +....n  = %d", matriz[n][n], total);
    }
  }
}
  



   return 0;
}
  • If you have a square matrix n x n then the diagonals, both primary and secondary, will have n elements. To print this variable amount of elements use a loop. (I didn’t understand your example, you didn’t show an array)

1 answer

1

See if, by any chance, this is what you wish:

#include <stdio.h>

int main() {
    int n=0, total=0;
    scanf("%d", &n);
    int matriz[n][n];
    printf("tr(A) =");
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            scanf("%d", &matriz[i][j]);
            if(i==j) {
                total += matriz[i][j];
                printf(" %s(%d)", (i==0) ? "" : "+ ", matriz[i][j]);
            }
        }
    }
    printf(" = %d\n", total);
    return 0;
}
  • That’s right bro, thank you. If I want to put two decimal places in the sums I have q exchange for %.2f and exchange the type for float?

  • I got here bro, thanks msm, helped a lot

  • Yes, change the matrix declaration, and total, to float and use the format %.2f on the printf.

  • I did that, thank you very much

Browser other questions tagged

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