If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Let's write a C++ program to create and display a diagonal matrix. In this example, we will use a 4x4 diagonal matrix, but you can modify the size and elements as per your requirement.
cppCopy code
#include <iostream> const int N = 4; // Size of the diagonal matrix void displayDiagonalMatrix(int matrix[N][N]) { std::cout << "Diagonal Matrix:" << std::endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } int main() { int diagonalMatrix[N][N] = {0}; // Initialize all elements to zero // Set diagonal elements (a, b, c, d) diagonalMatrix[0][0] = 5; diagonalMatrix[1][1] = 7; diagonalMatrix[2][2] = 3; diagonalMatrix[3][3] = 9; displayDiagonalMatrix(diagonalMatrix); return 0; }
In this program, we have a function
displayDiagonalMatrix
to print the elements of the diagonal matrix. The diagonal elements (5, 7, 3, 9) are set in themain
function, and all other elements are initialized to zero. ThedisplayDiagonalMatrix
function will display the matrix as follows:mathematicaCopy code
Diagonal Matrix: 5 0 0 0 0 7 0 0 0 0 3 0 0 0 0 9
This is a 4x4 diagonal matrix with diagonal elements 5, 7, 3, and 9. All other elements outside the diagonal are zero, fulfilling the properties of a diagonal matrix. You can modify the diagonal elements and matrix size according to your requirements.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform