
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Filling diagonal to make the sum of every row, column and diagonal equal of 3×3 matrix using c++
Suppose we have one 3x3 matrix, whose diagonal elements are empty at first. We have to fill the diagonal such that the sum of a row, column and diagonal will be the same. Suppose a matrix is like −
After filling, it will be −
Suppose the diagonal elements are x, y, z. The values will be −
- x = (M[2, 3] + M[3, 2])/ 2
- z = (M[1, 2] + M[2, 1])/ 2
- y = (x + z)/2
Example
#include<iostream> using namespace std; void displayMatrix(int matrix[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) cout << matrix[i][j] << " "; cout << endl; } } void fillDiagonal(int matrix[3][3]) { matrix[0][0] = (matrix[1][2] + matrix[2][1]) / 2; matrix[2][2] = (matrix[0][1] + matrix[1][0]) / 2; matrix[1][1] = (matrix[0][0] + matrix[2][2]) / 2; cout << "Final Matrix" << endl; displayMatrix(matrix); } int main() { int matrix[3][3] = { { 0, 3, 6 }, { 5, 0, 5 }, { 4, 7, 0 }}; cout << "Given Matrix" << endl; displayMatrix(matrix); fillDiagonal(matrix); }
Output
Given Matrix 0 3 6 5 0 5 4 7 0 Final Matrix 6 3 6 5 5 5 4 7 4
- Related Articles
- Matrix row sum and column sum using C program
- Golang program to calculate the sum of left diagonal matrix
- Python Program to calculate the sum of right diagonal the matrix
- Swift Program to calculate the sum of right diagonal of the matrix
- Swift Program to calculate the sum of left diagonal of the matrix
- Python Program to calculate the sum of left diagonal of the matrix
- Program to find diagonal sum of a matrix in Python
- JavaScript Program to Generate a matrix having sum of secondary diagonal equal to a perfect square
- Program to check diagonal matrix and scalar matrix in C++
- Zigzag (or diagonal) traversal of Matrix in C++
- C++ program to find the Sum of each Row and each Column of a Matrix
- Diagonal product of a matrix - JavaScript
- Convert a single column matrix into a diagonal matrix in R.
- How to find the sum of anti-diagonal elements in a matrix in R?
- Diagonal Sum of a Binary Tree in C++?

Advertisements