C++ Online Compiler
Example: Calculate Matrix Trace in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Calculate Matrix Trace #include <iostream> #include <vector> // Function to calculate the trace of a square matrix int calculateTrace(const std::vector<std::vector<int>>& matrix, int rows, int cols) { // Check if the matrix is square if (rows != cols) { std::cout << "Error: Trace is defined only for square matrices." << std::endl; return -1; // Indicate an error } int trace = 0; // Iterate through the main diagonal for (int i = 0; i < rows; ++i) { trace += matrix[i][i]; } return trace; } int main() { // Example matrix (3x3) std::vector<std::vector<int>> myMatrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int numRows = myMatrix.size(); int numCols = myMatrix[0].size(); // Assumes non-empty rows // Calculate and print the trace int traceValue = calculateTrace(myMatrix, numRows, numCols); if (traceValue != -1) { std::cout << "Trace of the matrix: " << traceValue << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS