Search This Blog

Wednesday, 2 March 2022

B5. Write a C Program to find the trace of a square matrix using function

 //B5. Write a C Program to find the trace of a square matrix using function
#include<stdio.h>
#include<conio.h>

int trace(int[10][10],int);   // Function prototype declaration.

void main()
{
    int a[10][10],m,n,i,j,sum;
    clrscr();
    printf("Enter the order of the square matrix\n");
    scanf("%d",&m);
    printf("Enter the matrix\n");
    for(i=0;i<m;i++)
        for(j=0;j<m;j++)
            scanf("%d",&a[i][j]);    // Read matrix elements.
    sum=trace(a,m);  // Call trace function.
    printf("Trace of the matrix is %d\n",sum);
    getch();
}

int trace(int a[10][10], int m)  //Function to find trace of matrix.
{
    int i,j,sum;
    sum=0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<m;j++)
        {
            if(i==j) // Condition to check for diagonal elements.
                sum=sum+a[i][j];
        }
    }
    return sum;
}

No comments :

Post a Comment

FREE Hit Counters