In this example we will find the Trace of matrix
#include <iostream>
using namespace std;
const int MAX = 100;
int FindTrace(int arr[][MAX], int n){
int sum = 0;
for(int i = 0; i < n; i++){
sum += arr[i][i];
}
return sum;
}
int main(){
int arr[][MAX] = {{2,5,8,4},
{3,5,8,4},
{8,4,9,5},
{4,9,6,2}};
cout<<"Trace of Matrix: "<<FindTrace(arr,4)<<endl;
return 0;
}
Output:
Trace of Matrix: 18
Explanation:
Step1: Constants and Function Declaration
const int MAX = 100;
This defines a constant MAX
which sets the maximum size of the matrix (100). It is used as the upper limit for the number of columns in the matrix.
Step2 : FindTrace
Function
int FindTrace(int arr[][MAX], int n){
int sum = 0;
for(int i = 0; i < n; i++){
sum += arr[i][i];
}
return sum;
}
This function computes the trace of the matrix. It takes two parameters:
arr[][MAX]
: A 2D array (matrix) of integers where the second dimension is limited byMAX
.n
: The size of the matrix (i.e., number of rows or columns since it’s a square matrix).
Within the function:
- It initializes
sum
to 0. - Then it loops over the diagonal elements of the matrix (elements where
i == j
), adding them tosum
. - Finally, it returns the calculated sum.
Step3: Main Function
int main(){
int arr[][MAX] = {{2,5,8,4},
{3,5,8,4},
{8,4,9,5},
{4,9,6,2}};
cout<<"Trace of Matrix: "<<FindTrace(arr,4)<<endl;
return 0;
}
In the main()
function:
- A 4×4 matrix
arr
is declared and initialized with specific values. - The function
FindTrace(arr, 4)
is called, passing the matrix and its size (4) as arguments. - The trace of the matrix is calculated and printed to the console.