Print Matrix in Z Form using Java



In this article, we will learn to print a matrix in a "Z" pattern in Java. It starts from the top-left corner, moves horizontally across the top row, then diagonally down through the center, and finally across the bottom row. This pattern creates a "Z" shape with selected elements from the matrix.

Problem Statement

Write a program in Java to print a matrix in Z form.

Input

my_arr[][] = { { 34, 67, 89, 0},{ 0, 1,0, 1 },{ 56, 99, 102, 21 },{78, 61, 40, 99}}

Output

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

Steps to print matrix in Z form

Following are the steps to print the matrix in Z form ?

  • Import all the necessary classes from the java.lang package and java.io package.
  • Define a z_shape method that uses the for loops and an if condition to print the top row, traverse diagonally to form the center of "Z," and print the bottom row.
  • In the main method, declare a 4x4 matrix and call the z_shape method to display the matrix in the "Z" form.

Java program to print matrix in Z form

Below is the Java program to print matrix in Z form ?

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

Code explanation

In the above program, a z_shape function is defined to follow the "Z" pattern. It first iterates over the top row, printing each element, then moves diagonally from the top-right to the bottom-left. Finally, it prints the entire bottom row. The main function initializes a matrix, calls z_shape with the matrix, and outputs the pattern on the console. This way, only specific elements are selected to create a "Z" shape output.

Updated on: 2024-10-29T18:51:04+05:30

649 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements