JAVA Program to Print the Diagonals of a Matrix

JAVA Program to Print the Diagonals of a Matrix  - ISC Computer
JAVA Program to Print the Diagonals of a Matrix  - ISC Computer

Here is  the JAVA Program to Print the Diagonals of a Matrix

We are uploading these types of program. However, if you need fully compiled solution of any type of Java program then simply leave a comment below, we will help you at the earliest. 😊😊

 import java.util.*;  
 class Print_Both_Diagonals_With_Their_Sum  
 {  
   public static void main()  
   {  
     Scanner sc=new Scanner(System.in);  
     int SumDiagonal=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];  
     for(int i=0;i<r;i++)  
     {  
       for(int j=0;j<c;j++)  
       {  
         System.out.print("Enter the Element of Matrix:");  
         arr[i][j]=sc.nextInt();  
       }  
     }  
     System.out.println("Input Matrix:");  
     for(int i=0;i<r;i++)  
     {  
       for(int j=0;j<c;j++)  
       {  
         System.out.print(arr[i][j]+"\t");  
       }  
       System.out.println(" ");  
     }  
     System.out.println("Diagonal Elements:");  
     for(int i=0;i<r;i++)  
     {  
       for(int j=0;j<c;j++)  
       {  
         if(i==j)  
         {  
           SumDiagonal=SumDiagonal+arr[i][j];  
           System.out.print(arr[i][j]+"\t");  
         }  
         else if(i+j==r-1 && j!=i)  
         {  
           SumDiagonal=SumDiagonal+arr[i][j];  
           System.out.print(arr[i][j]+"\t");  
         }  
         else  
           System.out.print("\t");  
       }  
       System.out.println(" ");  
     }  
     System.out.println("Sum of Both Diagonal Elements:"+SumDiagonal);  
   }  
 }  
 ------------  
 OUTPUT:-  
 -----------  
 Enter the number of Rows:  
 4  
 Enter the number of Columns:  
 4  
 Enter the Element of Matrix:1  
 Enter the Element of Matrix:5  
 Enter the Element of Matrix:6  
 Enter the Element of Matrix:3  
 Enter the Element of Matrix:2  
 Enter the Element of Matrix:4  
 Enter the Element of Matrix:5  
 Enter the Element of Matrix:6  
 Enter the Element of Matrix:2  
 Enter the Element of Matrix:3  
 Enter the Element of Matrix:9  
 Enter the Element of Matrix:8  
 Enter the Element of Matrix:7  
 Enter the Element of Matrix:5  
 Enter the Element of Matrix:3  
 Enter the Element of Matrix:2  
 --------------  
 Input Matrix:  
 1  5  6  3    
 2  4  5  6    
 2  3  9  8    
 7  5  3  2    
 ---------------  
 Diagonal Elements:  
 1      3    
   4  5      
   3  9      
 7      2    
 --------------  
 Sum of Both Diagonal Elements:34  

Checkout:- Sort Matrix in Ascending Order Java

Checkout:-  Sorting Rows of Matrix in Descending Order Java

Post a Comment

0 Comments