Loading your workspace…
Loading your workspace…
Read an n x n matrix, display it, and compute its trace, which is the sum of the elements on the main diagonal.
#include <stdio.h>
#define MAX 10
int main(void) {
int matrix[MAX][MAX];
int n, i, j, trace = 0;
printf("Enter the size n of the square matrix (1-%d):\n", MAX);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
printf("Error: size must be from 1 to %d\n", MAX);
return 1;
}
printf("Enter the %d x %d matrix:\n", n, n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("Matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%4d", matrix[i][j]);
}
printf("\n");
}
for (i = 0; i < n; i++) {
trace += matrix[i][i];
}
printf("Trace: %d\n", trace);
return 0;
}
Input
3
1 2 3
4 5 6
7 8 9Output
Enter the size n of the square matrix (1-10):
Enter the 3 x 3 matrix:
Matrix:
1 2 3
4 5 6
7 8 9
Trace: 15Input
1
42Output
Enter the size n of the square matrix (1-10):
Enter the 1 x 1 matrix:
Matrix:
42
Trace: 42A square matrix has the same number of rows and columns, so the main diagonal is the set of positions where the row index equals the column index. The trace is the sum of exactly those positions.
The trace is defined only for square matrices, which is why the program asks for one size n and reads an n x n block.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
3 1 2 3 4 5 6 7 8 9
Expected output
Enter the size n of the square matrix (1-10): Enter the 3 x 3 matrix: Matrix: 1 2 3 4 5 6 7 8 9 Trace: 15
1 42
Expected output
Enter the size n of the square matrix (1-10): Enter the 1 x 1 matrix: Matrix: 42 Trace: 42
The elements a[i][i], where the row and column index are equal.
The sum of the main diagonal elements.
A square matrix has equal rows and columns, so n fixes both dimensions.
It right-aligns each integer in a field of four characters so the columns line up.
Yes. Transposing swaps a[i][j] and a[j][i], which leaves the diagonal unchanged.
Back to all RCU 21BCA1C1P lab programs.