Sum of Each element Of matrix.....
Write a java program to calculate sum of each element of matrix using Random input :
import java.util.Random;
import java.util.Scanner;
public class SumOfMatrixElement {
static Random rx=new Random();
public static void main(String[] args) {
System.out.println("Enter a matrix : ");
int [][]mat=readmatrix();
dispMat(mat);
int sum=sumOfMatrix(mat);
System.out.println("Sum of matrix is : "+sum);
}
static int[][] readmatrix(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row size and column size :");
int row=sc.nextInt();
int col=sc.nextInt();
int mat[][]=new int[row][col];
System.out.println("Enter Elements in Table : ");
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
mat[i][j]=rx.nextInt(50);
}
}return mat;
}
static void dispMat(int mat[][]) {
for(int i=0;i<mat.length;i++) {
for(int j=0;j<mat[i].length;j++) {
System.out.print(mat[i][j]+" ");
}System.out.println();
}
}
static int sumOfMatrix(int [][]mat) {
int sum=0;
for(int i=0;i<mat.length;i++) {
for(int j=0;j<mat[i].length;j++) {
sum+=mat[i][j];
}
}
return sum;
}
}
Comments
Post a Comment