C Online Compiler
Example: Calculate Trace and Frobenius Normal of a Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Trace and Frobenius Normal of a Matrix #include <stdio.h> #include <math.h> // Required for sqrt and pow functions #define MAX_SIZE 10 // Maximum size for matrix // Function to calculate the trace of a square matrix double calculateTrace(int matrix[MAX_SIZE][MAX_SIZE], int size) { double trace = 0.0; for (int i = 0; i < size; i++) { trace += matrix[i][i]; // Sum main diagonal elements } return trace; } // Function to calculate the Frobenius normal of a matrix double calculateFrobeniusNormal(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols) { double sumOfSquares = 0.0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sumOfSquares += pow(matrix[i][j], 2); // Add square of each element } } return sqrt(sumOfSquares); // Return square root of the sum } int main() { int size; int matrix[MAX_SIZE][MAX_SIZE]; // Step 1: Get matrix size from the user printf("Enter the size of the square matrix (e.g., 3 for 3x3): "); scanf("%d", &size); if (size <= 0 || size > MAX_SIZE) { printf("Invalid size. Please enter a size between 1 and %d.\n", MAX_SIZE); return 1; // Indicate an error } // Step 2: Get matrix elements from the user printf("Enter the elements of the matrix row by row:\n"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { printf("Enter element [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } // Step 3: Print the entered matrix (optional) printf("\nEntered Matrix:\n"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { printf("%4d ", matrix[i][j]); } printf("\n"); } // Step 4: Calculate and print the trace double trace = calculateTrace(matrix, size); printf("\nTrace of the matrix: %.2f\n", trace); // Step 5: Calculate and print the Frobenius Normal // For a square matrix, rows and cols are the same as 'size' double normal = calculateFrobeniusNormal(matrix, size, size); printf("Frobenius Normal of the matrix: %.2f\n", normal); return 0; }
Output
Clear
ADVERTISEMENTS