Write a program to Check given matrix is identity
Example 1:
Input: matrix[][3]={{1,0,0},{0,1,0},{0,0,1}}
Output: Identity
Approach:
Java
public class MatrixIdentity {public static void main(String[] args) {// given input matrix as square// matrixint matrix[][] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };int n = 3;if (isIdentity(matrix, n))System.out.println("Identity");elseSystem.out.println("Not Identity");}private static boolean isIdentity(int[][] matrix, int n) {for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {// if i==j and matrix[i][j]!=1// then return falseif (i == j) {if (matrix[i][j] != 1)return false;}// else if i!=j and matrix[i][j]!=0// then return falseelse {if (matrix[i][j] != 0)return false;}}}return true;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check the given//matrix is identity or notbool isIdentity(int matrix[][3],int n){for(int i=0;i<n;i++){for(int j=0;j<n;j++){// if i==j and matrix[i][j]!=1//then return falseif(i==j){if(matrix[i][j]!=1)return false;}//else if i!=j and matrix[i][j]!=0//then return falseelse{if(matrix[i][j]!=0)return false;}}}return true;}int main(){//given input matrix as square//matrixint matrix[][3]={{1,0,0},{0,1,0},{0,0,1}};int n=3;if(isIdentity(matrix,n))cout<<"Identity\n";elsecout<<"Not Identity\n";}
No comments:
Post a Comment