Java Program to Print Matrix in Z form

JavaServer Side ProgrammingProgramming

To print matrix in Z form, the Java code is as follows −

Example

 Live Demo

import java.lang.*;
import java.io.*;
public class Demo{
   public static void z_shape(int my_arr[][], int n){
      int i = 0, j, k;
      for (j = 0; j < n - 1; j++){
         System.out.print(my_arr[i][j] + " ");
      }
      k = 1;
      for (i = 0; i < n - 1; i++){
         for (j = 0; j < n; j++){
            if (j == n - k){
               System.out.print(my_arr[i][j] + " ");
               break;
            }
         }
         k++;
      }
      i = n - 1;
      for (j = 0; j < n; j++)
      System.out.print(my_arr[i][j] + " ");
      System.out.print("\n");
   }
   public static void main(String[] args){
      int my_arr[][] = { { 34, 67, 89, 0},{ 0, 1,0, 1 },{ 56, 99, 102, 21 },{78, 61, 40,       99}};
      System.out.println("The matrix is ");
      z_shape(my_arr, 4);
   }
}

Output

The matrix is
34 67 89 0 0 99 78 61 40 99

A class named Demo defines a function named ‘z_shape’, that iterates through the array, by following the shape of ‘z’. In the main function, the multidimensional array is defined, and the function is called by passing this array. The relevant output is displayed on the console.

raja
Published on 14-Jul-2020 07:03:25
Advertisements