Topic: Summing all the numbers in a 2D matrix Write a program that reads an N by
ID: 3553409 • Letter: T
Question
Topic: Summing all the numbers in a 2D matrix
Write a program that reads an N by N matrix and displays the sum of all its elements. Your program should be able to check the input array size and make sure to accept positive number only.
Here is the sample run:
Enter the size of the array: -5
Please input a positive number as the array size: 4
Enter a 4by4 matrix row by row
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum of the matrix is 136
Also compute the maximum and minimum number of the array, and the maximum and minimum number for each row.
Please make sure to include max's and min's.
Explanation / Answer
Output ::
run:
Enter the size of the array:
-5
Please input a positive number as the array size:
4
Enter a 4by4matrix row by row
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Minimum and maximum of 0rowth are 1 and 4
Minimum and maximum of 1rowth are 5 and 8
Minimum and maximum of 2rowth are 9 and 12
Minimum and maximum of 3rowth are 13 and 16
Sum of all elements is 136
Global minimum and maximum are 1 and 16
BUILD SUCCESSFUL (total time: 15 seconds)
import java.util.*;
import java.lang.*;
import java.io.*;
class Poilce
{
public static void main (String[] args) throws java.lang.Exception
{
int size;
String temp;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
size = scan.nextInt();
while(size <=0 )
{
System.out.println("Please input a positive number as the array size: ");
size = scan.nextInt();
}
System.out.println("Enter a "+size + "by" + size + "matrix row by row");
int i,j;
int arr[][] = new int[size][size];
int max,min,totmin,totmax;
int tot = 0;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
arr[i][j] = scan.nextInt();
}
}
totmin = arr[0][0];
totmax = arr[0][0];
for(i=0;i<size;i++)
{
max = arr[i][0];
min = arr[i][0];
for(j=0;j<size;j++)
{
if(min > arr[i][j])
min = arr[i][j];
if(max < arr[i][j])
max = arr[i][j];
tot = tot + arr[i][j];
}
if(min < totmin)
totmin = min;
if(max > totmax)
totmax = max;
System.out.println("Minimum and maximum of "+i+"rowth are "+min+" and "+max);
}
System.out.println("Sum of all elements is "+tot);
System.out.println("Global minimum and maximum are "+totmin+" and "+totmax);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.