Let's Code Diagonal Matrix

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 140:- Let's Code Diagonal Matrix

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 the main function, and all other elements are initialized to zero. The displayDiagonalMatrix 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.

8. Matrices

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support