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

1 Answer

0 votes
using System;

public class Program
{
	private static double CalculateNormal(int[][] matrix) {
		int normal = 0;

		for (int i = 0; i < matrix.Length; i++) {
			for (int j = 0; j < matrix.Length; j++) {
				normal += matrix[i][j] * matrix[i][j];
			}
		}

		return Math.Sqrt(normal);
	}

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

		for (int i = 0; i < matrix.Length; i++) {
			trace += matrix[i][i];
		}

		return trace;
	}
	
	public static void Main(string[] args)
	{
		int[][] matrix = new int[][]
        		{
        			new int[] {1, 1, 1, 1, 1},
        			new int[] {2, 2, 2, 2, 2},
        			new int[] {3, 3, 3, 3, 3},
        			new int[] {4, 4, 4, 4, 4},
        			new int[] {5, 5, 5, 5, 5}
        		};

		Console.WriteLine(CalculateTrace(matrix));

		Console.WriteLine(CalculateNormal(matrix));
	}
}





/*
run:
  
15
16.583123951777
  
*/

 



answered Feb 27, 2023 by avibootz

Related questions

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