C program to find the trace of a matrix; Through this tutorial, we will learn how to find the trace of a matrix using for loop, while loop and do while loop in c programs.
Programs to Find the Trace of a Matrix in C
- C Program to Find the Trace of a Matrix using For Loop
- C Program to Find the Trace of a Matrix using While Loop
- C Program to Find the Trace of a Matrix using Do While Loop
C Program to Find the Trace of a Matrix using For Loop
#include <stdio.h> int main() { int i, j, rows, columns, trace = 0; printf("Enter Matrix Rows and Columns = "); scanf("%d %d", &rows, &columns); int Tra_arr[rows][columns]; printf("Please Enter the Matrix Items = \n"); for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { scanf("%d", &Tra_arr[i][j]); } } for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { if (i == j) { trace = trace + Tra_arr[i][j]; } } } printf("The Trace Of the Matrix = %d\n", trace); }
The output of the above c program; is as follows:
Enter Matrix Rows and Columns = 2 2 Please Enter the Matrix Items = 1 2 3 4 The Trace Of the Matrix = 5
C Program to Find the Trace of a Matrix using While Loop
#include <stdio.h> int main() { int i, j, rows, columns, trace = 0; printf("Enter Matrix Rows and Columns = "); scanf("%d %d", &rows, &columns); int Tra_arr[rows][columns]; printf("Please Enter the Matrix Items = \n"); i = 0; while(i < rows) { j = 0; while(j < columns) { scanf("%d", &Tra_arr[i][j]); j++; } i++; } i = 0; while(i < rows) { j = 0; while(j < columns) { if(i == j) { trace = trace + Tra_arr[i][j]; } j++; } i++; } printf("The Trace Of the Matrix = %d\n", trace); }
The output of the above c program; is as follows:
Enter Matrix Rows and Columns = 2 2 Please Enter the Matrix Items = 3 4 5 6 The Trace Of the Matrix = 9
C Program to Find the Trace of a Matrix using Do While Loop
#include <stdio.h> int main() { int i, j, rows, columns, trace = 0; printf("Enter Matrix Rows and Columns = "); scanf("%d %d", &rows, &columns); int Tra_arr[rows][columns]; printf("Please Enter the Matrix Items = \n"); i = 0; do { j = 0; do { scanf("%d", &Tra_arr[i][j]); if (i == j) { trace = trace + Tra_arr[i][j]; } } while (++j < columns); } while (++i < rows); printf("The Trace Of the Matrix = %d\n", trace); }
The output of the above c program; is as follows:
Enter Matrix Rows and Columns = 2 2 Please Enter the Matrix Items = 5 6 7 8 The Trace Of the Matrix = 13