Interview Program – Matrix

Print matrix in Z form.

Input: mat[][] = {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output: 1 2 3 5 7 8 9





public class PrintTheMatrixOrder {

	public static void printTheMatrix(int mat[][]) {
		for (int i = 0; i < mat.length; i++) {
			System.out.print(mat[0][i] + " ");
		}

		int n = mat.length - 2;
		for (int i = 1; i < mat.length - 1; i++) {

			System.out.print(mat[i][n] + " ");

			n--;

		}

		for (int i = 0; i < mat.length; i++) {
			System.out.print(mat[mat.length - 1][i] + " ");
		}
	}

	public static void main(String[] args) {
		int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		printTheMatrix(mat);

	}

}

Thanks and Regards,
Solution provided by Nilmani Prashanth

About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *