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.
Related
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....
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);
}
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.
I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.
The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns
I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}
Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.
public void calculatePercentage(int exam[][])
{
int perc = 0;
for (int i = 0; i < examen.length; i++)
{
for (int[] score : exam)
perc += score;
perc /= exam.length;
}
}
Hello,
I am really stuck at this one. I want to create a new mathod calculatePercentages given the parameter exam[][]. The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row. The answer is probably quite simple, but I just don't know how to do it.
For a single array, I guess the code is:
double perc = 0;
for(int score : exam)
{
perc += score;
}
perc /= (exam.length);
return perc;
The exam[][] could look like:
|10 12 18 5 3 |
|12 3 5 15 20 |
|20 15 13 11 9 |
The output percentage[] should like:
{48,55,68} Each element of percentage[] is the sum of the elements of 1 row of exam[]
The double array exam holds 3 rows of elements. What the method has to do is simple calculate the sum of each row.
The name makes no sense, but it does what you want it to do.
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
sums[i] = sum;
}
return sums;
}
Also a double array would be double[], you are talking about two dimensional int arrays int[][]
EDIT
Pshemo pointed out a shorter solution is possible:
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++) {
for (int j = 0; j < exam[i].length; j++) {
sums[i] += exam[i][j];
}
}
return sums;
}
or even just
public int[] calculatePercentage(int exam[][]) {
int[] sums = new int[exam.length];
for (int i = 0; i < exam.length; i++)
for (int j = 0; j < exam[i].length; j++)
sums[i] += exam[i][j];
return sums;
}
but I still prefer the first one, for it's readability.
for (int i = 0; i < exam.length; i++) {
int sum = 0;
for (int j = 0; j < exam[i].length; j++) {
sum += exam[i][j];
}
}
using for each
for (int x[] : exam) {
for (int y : x) {
sum += y;
}
}