Question
program to find sum of non-boundary elements of matrix
Matrix = [9, 8, 7]
[6, 5, 4]
[3, 2, 1]
SUM OF NON-BOUNDARY ELEMENTS OF MATRIX:5
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 SumNonBoundaryElementsOfMatrix
{
public static void main(String[] args)
{
int row=0,col=0,i=0,j=0,sum=0;
int a[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ROW OF MATRIX");
row=sc.nextInt();
System.out.println("ENTER THE NUMBER OF COLUMN OF MATRIX");
col=sc.nextInt();
a=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
a[i][j]=sc.nextInt();
}
}
//printing the matrix
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
//calculating sum
System.out.println("Matrix:");
for(i=1;i< row-1;i++)
{
for(j=1;j< col-1;j++)
{
sum=sum+a[i][j];
}
}
System.out.println("SUM OF NON-BOUNDARY ELEMENTS OF MATRIX:"+sum);
}
}
Python
import numpy as np
row=int(input("Enter number of rows:"))
columns=int(input("Enter number of columns:"))
matrix=np.empty([row,columns],dtype=np.int)
# Taking input from user
print("Enter elements in matrix:")
for i in range(0,row):
for j in range(0,columns):
print("(",(i+1),",",(j+1),")",":",end="")
matrix[i,j]=int(input())
#printing the matrix
print("Matrix:")
for i in range(0, row):
print(matrix[i])
#calculating sum
sum=0
for i in range(1,row-1):
for j in range(1,columns-1):
sum=sum+matrix[i,j]
#You can replace from line 16 to 19
#with sum = matrix.sum()
print("Sum of non-boundary elements:",sum)