From 5d71be06a8b48a3e76302bf8c7db90db5e146538 Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Sat, 31 Aug 2024 02:07:24 +0530 Subject: [PATCH] Add OOP/Java/Lab/Week4/TraceNorm.java --- OOP/Java/Lab/Week4/TraceNorm.java | 40 +++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 OOP/Java/Lab/Week4/TraceNorm.java diff --git a/OOP/Java/Lab/Week4/TraceNorm.java b/OOP/Java/Lab/Week4/TraceNorm.java new file mode 100644 index 0000000..a403045 --- /dev/null +++ b/OOP/Java/Lab/Week4/TraceNorm.java @@ -0,0 +1,40 @@ +import java.util.Scanner; + +class TraceNorm { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("Enter the size of the square matrix: "); + int n = sc.nextInt(); + + double[][] matrix = new double[n][n]; + + System.out.println("Enter the elements of the matrix:"); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] = sc.nextDouble(); + } + } + + // trace + double trace = 0; + for (int i = 0; i < n; i++) { + trace += matrix[i][i]; + } + + // norm + double normSquared = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + normSquared += matrix[i][j] * matrix[i][j]; + } + } + double norm = Math.sqrt(normSquared); + + System.out.println("Trace of the matrix: " + trace); + System.out.println("Norm of the matrix: " + norm); + + sc.close(); + } +}