C++ program to check whether a matrix is scalar or not
In this article, we will learn how to check whether a given matrix is scalar or not in C++. A square matrix is said to a scalar if all the diagonal elements of the matrix are equal to each other and non-diagonal elements are equal to zero.
Examples
Input: matrix = {{2, 0, 0, 0}, {0, 2, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 2}} Output: Scalar matrix Input: matrix = {{1, 2, 0, 0}, {2, 0, 0, 0}, {2, 0, 0, 0}, {1, 4, 0, 0}} Output: Non-scalar matrix
Check whether a matrix is scalar or not in C++
1. Traverse the matrix using two nested loops and check
- If non-diagonal are not equal to zero then return false
if (i != j && matrix[i][j] != 0)
2. Now check diagonal elements are equal to each other if equal return true.
#include <bits/stdc++.h> using namespace std; #define n 3 // function to check matrix is scalar or not bool scalar_matrix(int matrix[n][n]){ // check whether non diagonal elements are equal to zero for (int i = 0;i<n;i++){ for(int j=0;j<n;j++){ if (i != j && matrix[i][j] != 0) return false; } } // check whether diagonal elements are equal to each other. for(int i =0;i<n-1;i++) if(matrix[i][i] != matrix[i+1][i+1]) return false; return true; } int main(){ int matrix[n][n] = {{5, 0, 0}, {0, 5, 0}, {0, 0, 5}}; for (int i = 0;i<n;i++){ for(int j=0;j<n;j++){ cout<<matrix[i][j]<<" "; } cout<<endl; } if(scalar_matrix(matrix)) cout<<"Scalar matrix"<<endl; else cout<<"Non scalar matrix"<<endl; return 0; }
Output
5 0 0 0 5 0 0 0 5 Scalar matrix
Also, read
Leave a Reply