java multidimensional arrays row sum and column sum - java

public static void main(String[] args) {
int rows, cols, j, i;
Scanner sc = new Scanner(System.in);
System.out.println("enter no of rows and columns respectively");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows+1][cols+1];
System.out.println("enter elements");
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
matrix[i][j] = sc.nextInt();
}
}
System.out.println("after sum");
int grandtotal = 0;
for(i = 0; i < rows; i++)
{
int rowsum = 0;
int colsum = 0;
for(j = 0; j < cols; j++)
{
rowsum += matrix[i][j];
colsum += matrix[j][i];
}
matrix[i][j] = rowsum;
grandtotal += rowsum;
matrix[j][i] = colsum;
}
j = cols;
matrix[i][j] = grandtotal;
The above code is working fine, but my question is: using this logic, how can I find the grandtotal for a matrix if the number of rows and columns are not the same? And tell me if there are any flaws with my current code.

There is no flaw in your code.Now coming to the point when the number of rows and columns are different.
The statement
matrix[j][i] = colsum;
now would give incorrect result because now number of rows and number of columns are different.
This can be solved very easily by just changing the statement
colsum += matrix[j][i];
to:
matrix[rows][j] += matrix[i][j];
and now you do not need the statement
matrix[j][i] = colsum;
So with these simple modifications, the code for different number of columns and rows would be:
for( i = 0;i < rows;i++)
{
int rowsum=0;
for( j = 0;j < cols;j++)
{
rowsum += matrix[i][j];
matrix[rows][j] += matrix[i][j];
}
matrix[i][j] = rowsum;
grandtotal += rowsum;
}
Keep Rest of the code same.

Related

Logical error while inserting elements in to Two dimensional array using Scanner

I'm trying to sum of rows of Matrix
When I just put elements in 2D array output is right but when I'm trying using Scanner output result is different
SAMPLE INPUT
2
1 2
3 4
Output:
3
7
Below code result correct
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int a[][] = {
{1, 2,},
{ 3, 4}
};
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
Result incorrect if I'm trying with Scanner
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int column = sc.nextInt();
int [][] a = new int[row][column];
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
With the sample input you've provided, you shouldn't be reading the number of rows and columns, but just a single int for the number of both rows and columns:
int size = sc.nextInt();
int [][] a = new int[size][size];
for (int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
a[i][j] = sc.nextInt();
}
}
I do not see any logical problem with your code. However, it is equally important to keep your code clean and user friendly. I recommend you address the following points if you are serious about programming:
The following declaration is unnecessary:
rows = a.length;
cols = a[0].length;
You can simply use row and column instead of creating rows and cols for the same thing.
You should remove all such unnecessary things which create noise in your code.
You have missed printing the sum of each column i.e.
System.out.println(sumCol);
You do not need to declare throws IOException with main for this code.
You should always display a message describing the input; otherwise, the user remains clueless about what he/she is supposed to input.
Given below is the code incorporating these comments:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int row = sc.nextInt();
System.out.print("Enter the number of columns: ");
int column = sc.nextInt();
int[][] a = new int[row][column];
for (int i = 0; i < row; i++) {
System.out.println("Enter " + column + " integers: ");
for (int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int sumRow, sumCol;
// Calculates sum of each row of given matrix
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < column; j++) {
sumRow = sumRow + a[i][j];
}
System.out.println("Sum of row " + i + ": " + sumRow);
}
// Calculates sum of each column of given matrix
for (int i = 0; i < column; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + a[j][i];
}
System.out.println("Sum of column " + i + ": " + sumCol);
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 4
Enter 4 integers:
1 9 2 8
Enter 4 integers:
2 8 3 7
Enter 4 integers:
3 7 4 6
Sum of row 0: 20
Sum of row 1: 20
Sum of row 2: 20
Sum of column 0: 6
Sum of column 1: 24
Sum of column 2: 9
Sum of column 3: 21

Is there a way to fix my two dimensional array problem

How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....

Sum the elements of 2D array

I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
        for(j=0;j
        {
                if(j>i)
                    d1+=a[i][j];. // Above the diagon
                else
                    if(i>j)
                        d2+=a[i][j];. // Below the diagonal
        }
    

matrix column sum java

I am working just recently in Java. And I am still struggling a little bit with Java. The task is to sum the columns and the rows respectively the example looks like that.
I managed to get the sum of the columns, but I always end up having the first row repeated in my desired output, how can I delete that error. And just have the desired column sums.
How does it work for sum of rows respectively?
Thank you very much for your help in advance
The code looks like that:
public class MatrixColumnSums {
public static void main(String[] args) {
// TODO Auto-generated method stub
double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
System.out.println( "A");
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
// creating another matrix to store the sum of columns matrices
double c[] = new double [a[0].length];
// Adding and printing addition of 2 matrices
System.out.println("C");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
{
c[j] += a[i][j];
System.out.print(c[j] + "\t");
}
System.out.println();
}
}
}
The output looks like the following:
A
1.0 2.0 3.0
4.0 5.0 6.0
C
1.0 2.0 3.0 ( <= I want to get this row deleted)
5.0 7.0 9.0 ( I just want to have this as my output)
**Matrix column sum **
doOneColumnSum method sum one column.
private static double doOneColumnSum(double[][] arr, int col){
double total = 0;
for (int row = 0; row < arr.length; row += 1){
total += arr[row][col];
}
return total;
}
doColumnSums method sum all column using doOneColumnSum method
public static double[] doColumnSums(double[][] arr)
{
int numColumns = arr[0].length;
double[] result = new double[numColumns];
for (int col = 0; col < numColumns; col += 1)
{
result[col] = findOneColumnSum(arr, col);
}
return result;
}
Don't print when summing the c matrix, just print once at the end:
// sum the columns first
for (int i=0; i < a.length; i++) {
for (int j=0; j < a[0].length; j++) {
c[j] += a[i][j];
}
}
// then iterate c[] once at the end and print it
for (int j=0; j < a[0].length; j++) {
System.out.print(c[j] + "\t");
}
Note that we could have added if logic to your original nested loop to only print c after the summation is complete, but what I wrote above seems more appealing from a separation of concerns point of view.

Print sums of each column & sums of each row of Matrix in Java

I'm stuck on how to find the sums of each column & row of Matrix in Java. I don't know how to find the result of column and row separately. Thank you in advance.
public static void main(String[] args) {
double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
double[] b = new double[a[0].length];
// row sums
Use two nested loops:
for(int i = 0; i < b.length; i++) {
b[i] = 0;
for(int j = 0; j < a.length(); j++) {
b[i] += a[j][i];
}
}
You get the sum of a one-dimensional segment of a n-dimensional array, you will need to form a nested loop to iterate through n-dimensional array, with a loop for each dimension. At the deepest step of each iteration, once you are inside the inner-most nested loop, you can increment the total value by the value referenced at that particular point in iteration.
double[][] a = new double[2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
System.out.print(a[row][col] + "\t");
}
System.out.println("");
}
double[] rowTotals = new double[a.length];
double[] colTotals = new double[a[0].length];
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
rowTotals[row] += a[row][col];
colTotals[col] += a[row][col];
}
}
I notice in your question you wanted to find the row and column totals separately. If this is a must (I can't see why), you can simply duplicate the nested loop and dedicate one loop for column totals and one for row totals.
//Considering
// row1: 123
// row2: 456
List<Double> colsSum = new ArrayList<>(Collections.nCopies(a[0].length, 0.0));
List<Double> rowsSum = new ArrayList<>();
for(int i = 0; i < a.length; i++){
double row = 0;
for(int j = 0; j < a[i].length; j++){
row += a[i][j];
colsSum.set(j, colsSum.get(j) == 0 ? a[i][j]
: colsSum.get(j) + a[i][j]);
}
rowsSum.add(row);
}

Categories