This program reads two matrices of the same order, computes either their sum or difference (user’s choice), and then finds the trace of the result. The trace of a matrix is the sum of its main diagonal elements (positions where row index equals column index). It is defined for any matrix, not just square ones — for a rectangular M×N matrix, the diagonal has min(M,N) elements.
The original used conio.h, void main(), clrscr(), a function prototype declared inside main() (invalid placement in C89), and broken \n in format strings.
| Property | Formula | Example (2×2) |
|---|---|---|
| Addition | (A+B)[i][j] = A[i][j] + B[i][j] | [1+5, 2+6; 3+7, 4+8] = [6,8;10,12] |
| Subtraction | (A-B)[i][j] = A[i][j] – B[i][j] | [1-5, 2-6; 3-7, 4-8] = [-4,-4;-4,-4] |
| Trace of result | tr(C) = Σ C[i][i] | tr([6,8;10,12]) = 6+12 = 18 |
C Program: Matrix Addition, Subtraction, and Trace
/* Matrix addition, subtraction, and trace in C
* Compile: gcc -ansi -Wall -Wextra matadd.c -o matadd */
#include <stdio.h>
#define MAX 10
void print_matrix(int a[][MAX], int r, int c)
{
int i, j;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++)
printf("%4d", a[i][j]);
printf("\n");
}
}
int trace(int a[][MAX], int r, int c)
{
int i, sum = 0;
int limit = (r < c) ? r : c; /* diagonal length = min(r,c) */
for (i = 0; i < limit; i++)
sum += a[i][i];
return sum;
}
int main(void)
{
int A[MAX][MAX], B[MAX][MAX], result[MAX][MAX];
int i, j, m, n, op;
printf("Enter matrix order (rows cols): ");
if (scanf("%d %d", &m, &n) != 2 || m<1||m>MAX||n<1||n>MAX) {
printf("Invalid dimensions.\n"); return 1;
}
printf("Enter elements of matrix A (%dx%d):\n", m, n);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
if (scanf("%d", &A[i][j]) != 1) { printf("Invalid.\n"); return 1; }
printf("Enter elements of matrix B (%dx%d):\n", m, n);
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
if (scanf("%d", &B[i][j]) != 1) { printf("Invalid.\n"); return 1; }
printf("\nMatrix A:\n"); print_matrix(A, m, n);
printf("Matrix B:\n"); print_matrix(B, m, n);
printf("Enter operation (1=Add, 2=Subtract): ");
if (scanf("%d", &op) != 1 || (op != 1 && op != 2)) {
printf("Enter 1 or 2.\n"); return 1;
}
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
result[i][j] = (op == 1) ? A[i][j] + B[i][j]
: A[i][j] - B[i][j];
if (op == 1) printf("\nA + B:\n");
else printf("\nA - B:\n");
print_matrix(result, m, n);
printf("Trace of result = %d\n", trace(result, m, n));
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra matadd.c -o matadd
./matadd
Sample Output
Enter matrix order (rows cols): 2 2 Enter elements of matrix A (2x2): 1 2 3 4 Enter elements of matrix B (2x2): 5 6 7 8 Matrix A: 1 2 3 4 Matrix B: 5 6 7 8 Enter operation (1=Add, 2=Subtract): 1 A + B: 6 8 10 12 Trace of result = 18
Code Explanation
- Both matrices have the same dimensions — matrix addition and subtraction are only defined when both matrices have the same order (same number of rows and columns). This program uses a single M×N order for both A and B, which enforces this constraint at input time.
- Ternary operator for add/subtract —
result[i][j] = (op == 1) ? A[i][j] + B[i][j] : A[i][j] - B[i][j];handles both operations in a single loop. An alternative is to use aswitchwith separate loops per case, but the ternary keeps the code compact without sacrificing readability. - Trace function — declared at file scope (before
main), not inside it. In C89, a function declaration inside a block is technically a forward declaration, but placing helper functions at file scope is the standard practice. Thetracefunction computesmin(r,c)as the diagonal length, which correctly handles non-square matrices. - Trace of a non-square matrix — the trace is defined even for rectangular matrices: tr([1,2,3; 4,5,6]) = a[0][0] + a[1][1] = 1 + 5 = 6. The diagonal stops when either the row or column index runs out.
What This Program Teaches
- Element-wise matrix operations — addition and subtraction apply the same scalar operation to every pair of corresponding elements. This is the foundation of matrix arithmetic. Multiplication, by contrast, is not element-wise and requires a triple-nested loop.
- Matrix trace — the trace is invariant under cyclic permutations (tr(ABC) = tr(BCA) = tr(CAB)) and equals the sum of eigenvalues. It appears in physics (trace of a stress tensor), statistics (Hutchinson trace estimator), and numerical methods (spectral radius bounds).
- Reusable helper functions — extracting print_matrix and trace as separate functions avoids copy-pasting the nested loop body. Any change to the output format requires editing one place instead of several. Functions are the primary tool for reducing code duplication in C.
Related Programs
- Sum of Matrix Elements in C
- Matrix Equality Check in C
- Swap Matrix Diagonals in C
- Identity Matrix Check in C
- Structures in C — Complete Guide
Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
|
C Programming: A Modern Approach — K.N. King (India) |
(US)
Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.
1 comment on “C Program for Matrix Addition, Subtraction and Trace”
c program to find trace of a matrix