How to calculate the normal and trace of square matrix in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

#define SIZE 5

double CalculateNormal(int matrix[][SIZE]) {
    int normal = 0;
    
    for (int i = 0; i < SIZE; i++)
        for (int j = 0; j < SIZE; j++)
            normal += matrix[i][j] * matrix[i][j];
    
    return sqrt(normal);
}

int CalculateTrace(int matrix[][SIZE]) {
    int trace = 0;

    for (int i = 0; i < SIZE; i++)
        trace += matrix[i][i];
    
    return trace;
}

int main(void)
{
    int matrix[][SIZE] = { {1, 1, 1, 1, 1},
                           {2, 2, 2, 2, 2},
                           {3, 3, 3, 3, 3},
                           {4, 4, 4, 4, 4},
                           {5, 5, 5, 5, 5} };
    
    printf("%d\n", CalculateTrace(matrix));
   
    printf("%lf\n", CalculateNormal(matrix));

    return 0;
}




/*
run:

15
16.583124

*/


 



answered Feb 26, 2023 by avibootz
edited Feb 27, 2023 by avibootz

Related questions

1 answer 131 views
1 answer 126 views
1 answer 175 views
1 answer 134 views
1 answer 139 views
...