Question
program to print right and left diagonals of matrix
Matrix = [9, 8, 7]
[6, 5, 4]
[3, 2, 1]
DIAGONALS OF MATRIX
9 7
5
3 1
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class printDiagonalOfMatrix
{
public static void main(String[] args)
{
int size=0,i=0,j=0;
int a[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE SIZE OF MATRIX");
size=sc.nextInt();
a=new int[size][size];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
System.out.print("("+(i+1)+","+(j+1)+"):");
a[i][j]=sc.nextInt();
}
}
System.out.println("MATRIX:");
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("DIAGONALS OF MATRIX:");
for(i=0;i< size;i++)
{
for(j=0;j< size;j++)
{
if(i==j || (i+j==size-1))
{
System.out.print(a[i][j]+" ");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
}
}
Python
import numpy as np
size=int(input("Enter size of Matrix:"))
matrix=np.empty([size,size],dtype=np.int)
# Taking input from user
print("Enter elements in matrix:")
for i in range(0,size):
for j in range(0,size):
print("(",(i+1),",",(j+1),")",":",end="")
matrix[i,j]=int(input())
#printing the matrix
print("Matrix:")
for i in range(0, size):
print(matrix[i])
#Printing Diagonal elements
print("Diagonal Elements:")
for i in range(0,size):
for j in range(0,size):
if(i==j or (i+j==size-1)):
print(matrix[i,j],end=" ")
else:
print(end=" ")
print()