Print Boundary Elements Of Matrix Trick 2024 | topperbhai.com

Java program to print boundary elements of matrix 

Java Program to Print Boundary Elements Of Matrix

In this tutorial, we will write a java program to print boundary elements of matrix.



First, we will write the algorithm to print boundary elements of matrix, then we will write the compiled java code of this program.



Our task is pretty simple. We have to ask the user to input a matrix and then just print boundary elements of matrix.


 

A square matrix of size r*c will be passed as input by the user, then the program will just print boundary elements of matrix.


 
We will just access the boundary elements using the below approach.



Java Program to Print Boundary Elements of Matrix Algorithm:

Step 1: Enter the number of Rows (r).

Step 2: Enter number of Columns (c).

Step 3: Read the elements of Matrix (arr[i][j]).
Step 4:
Read all boundary elements using for loop (k and l).
       

Step 5: Print Input Matrix.

Step 6: Print Boundary Elements.

 

Java Program to Print Boundary Elements Of Matrix

 import java.util.*;  
 class Only_Boundary_Elements  
 {  
   public static void main()  
   {  
     Scanner sc=new Scanner(System.in);  
     int i,j,Temp,n=0;  
     System.out.println("Enter the Number of Rows");  
     int r=sc.nextInt();  
     System.out.println("Enter the Number of Columns");  
     int c=sc.nextInt();  
     int arr[][]=new int[r][c];  
     System.out.println("Enter the Elements of Matrix");  
     for(i=0;i<r;i++)  
     {  
       for(j=0;j<c;j++)  
       {  
         arr[i][j]=sc.nextInt();  
       }  
     }  
     System.out.println("Input Matrix Is :-");  
     for(i=0;i<r;i++)  
     {  
       for(j=0;j<c;j++)  
       {   
         System.out.print(arr[i][j]+" ");  
       }  
       System.out.println(" ");  
     }  
     System.out.println("OUTPUT:\nDESIRED MATRIX");  
     for(int k=0;k<r;k++)  
     {  
       for(int l=0;l<c;l++)  
       {  
         if(k==0 || k==r-1)  
         {  
          System.out.print(arr[k][l]+"\t");  
         }  
         else if(l==0 || l==c-1)  
         {  
           System.out.print(arr[k][l]+"\t");  
         }  
         else  
         System.out.print(" \t");  
       }  
       System.out.println("");  
     }  
   }  
 }  
 ---------------------------  
 Enter the Number of Rows  
 3  
 Enter the Number of Columns  
 3  
 Enter the Elements of Matrix  
 1  
 4  
 5  
 2  
 6  
 3  
 9  
 8  
 7  
 Input Matrix Is :-  
 1 4 5   
 2 6 3   
 9 8 7   
 -----------  
 OUTPUT:  
 -----------  
 DESIRED MATRIX  
 1     4     5       
 2           3       
 9     8     7  
 
 

Post a Comment

0 Comments