Q:

Java program to print boundary elements of the matrix

belongs to collection: Java Array Programs

0

Given a matrix and we have to print its boundary elements using java program.

Example:

    Input:
    Row: 3
    Cols: 4
    Input matrix is:
    1 2 5 6 
    9 8 7 3
    6 5 7 4

    Output:
    Matrix boundary elements
    1	2	5	6	
    9	 	 	3	
    6	5	7	4

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print boundary elements of a matrix

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExArrayPrintBoundrayElements {
  public static void main(String args[]) throws IOException {
    // declare the objects.
    int i, j, m, n;

    // create the object of buffer class.
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    // enter rows and columns.
    System.out.print("Enter the rows : ");
    m = Integer.parseInt(br.readLine());
    System.out.print("Enter the columns : ");

    n = Integer.parseInt(br.readLine());

    //Creating the array
    int A[][] = new int[m][n];

    // Input the elements.
    for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        // enter elements.
        System.out.println("Enter the elements : ");
        A[i][j] = Integer.parseInt(br.readLine());
      }
    }

    // this will print the boundary elements.
    System.out.println("The Boundary Elements are:");
    for (i = 0; i < m; i++) {
      for (j = 0; j < n; j++) {
        // condition for obtaining the boundary elements
        if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
          System.out.print(A[i][j] + "\t");
        else
          System.out.print(" \t");
      }
      System.out.println();
    }
  }
}

Output

Enter the rows : 3
Enter the columns : 4

Enter the elements : 1
Enter the elements : 2
Enter the elements : 5
Enter the elements : 6
Enter the elements : 9
Enter the elements : 8
Enter the elements : 7
Enter the elements : 3
Enter the elements : 6
Enter the elements : 5
Enter the elements : 7
Enter the elements : 4

The Boundary Elements are:
1	2	5	6	
9	 	 	3	
6	5	7	4	

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check whether a matrix is symmetri... >>
<< Java program to create a matrix and fill it with p...