Answer to Question #293388 in Java | JSP | JSF for saira aslam

Question #293388

Write a method called isIdentityMatrix which will take a two-dimensional integer

array as argument, and returns true if the array is an identity matrix, or false otherwise.

You may use the following header for this method:

static boolean isIdentityMatrix(int[][] array)

A matrix is an identity matrix if it is a square matrix, and all its elements at the left

diagonal are ones, and all other elements are zeroes.

For example, the following matrix is an identity matrix and the method should return true

if we pass it to the isIdentityMatrix matrix as two-dimensional:

1 0 0 0 0

0 1 0 0 0

0 0 1 0 0

0 0 0 1 0

0 0 0 0 1

For the following two-dimensional array, the method should return false because there

are some non-zero elements in the matrix.

1 0 0 5 0

0 1 0 2 0

0 3 1 0 0

0 0 0 1 5

0 5 0 0 1

Similarly, for the following two-dimensional array, the method should return false

because some elements at left diagonal are not ones.

1 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 1 0

0 0 0 0 1


1
Expert's answer
2022-02-03T08:04:34-0500


public class App {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		int[][] array = { { 1, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0 },
				{ 0, 0, 0, 0, 1 } };


		if (isIdentityMatrix(array)) {
			System.out.println("The array is an identity matrix");
		} else {
			System.out.println("The array is NOT an identity matrix");
		}


	}


	static boolean isIdentityMatrix(int[][] array) {
		if (array == null || array.length != array[0].length) {
			return false;
		}
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[0].length; j++) {
				if ((i != j && array[i][j] != 0) || (i == j && array[i][j] != 1)) {
					return false;
				}
			}
		}
		return true;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS