How to print column total directly below each column in 2D array - java

My code requests the user to input array size, as well as values. I want to sum each column and display the total below each column, as in a table.
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.println("Total column: " + columnSum);
}

You can try this
String message="Total Column:";
Scanner input=new Scanner(System.in);
int row=2,column=3;
StringBuilder array_output=new StringBuilder();
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
array_output.append(String.format("%"+message.length()+"s",""));
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
System.out.print(message+" \t");
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.print(columnSum+"\t");
}

Notice only the additional changes that added on top of your code snippet.
int a[][] = new int[row + 1][column]; // +1 for total/sum
for (int j = 0; j < column; j++){
//... rest of the logic correct
a[row][j] = columnSum;
}
//Print the result
for (int i=0; i < row+1; i++) {
for (int j=0; j < column; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}

Your problem is that you are using the same variable columnSum in each interation. If you want a sum for each column then columnSum needs to be an array with an entry for each column. Then you can print that array as last output row.
I recommend to give the variables i and j a more meaningful name. Call row rows and i row and you can read you code more easily.

Just create an array of result. Now while entering data in input array, prepare your result array by adding column data in result array. In last print it. It will same time and 1 extra for loop.
int a[][] = new int[row][column];
int result[] = new int[column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
result[j] = result[j]+a[i][j];//creating array of column sum
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < result.length; j++){
System.out.print(result[j] + "\\t");
}

Related

How to get the sum for each row?

I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output:
The problem is every time the maximum sum is the third row how to solve these issues.
int [][] scores = new int[4][3];
for (int i=0; i<scores.length; i++)
{
System.out.print("Enter values for row "+i+": ");
for (int j=0; j<scores[i].length;j++)
scores[i][j] = kbd.nextInt();
}
int sum, sumMax, ii=0;
for (int i=0; i<scores.length; i++)
{
sum =0; sumMax = 0; ii=0;
for (int j=0; j<scores[i].length;j++)
{
sum += scores[i][j];
if (sum>sumMax)
{
sumMax = sum;
ii = i;
}
}
}
System.out.println("Row "+ii+" has the maximum sum");
System.out.print("Row "+ii+" has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
To print a specific row, you need one loop only
System.out.print("Row " + ii + " has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
Or with Arrays.toString
System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row
int sum, sumMax = Integer.MIN_VALUE, ii = 0;
for (int i = 0; i < scores.length; i++) {
sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
if (sum > sumMax) {
sumMax = sum;
ii = i;
}
}
You can add the rows while getting the input from scanner and store them in an array. Then you can search for the max value in the sums array:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int[][] scores = new int[4][3];
int[] rowSums = new int[4];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter values for row " + i + ": ");
for (int j = 0; j < scores[i].length; j++){
scores[i][j] = kbd.nextInt();
rowSums[i] += scores[i][j];
}
}
int index = 0;
int maxSum = rowSums[index];
for(int i = 1; i < rowSums.length; i++){
if(rowSums[i] > maxSum){
maxSum = rowSums[i];
index = i;
}
}
System.out.println("Row "+index+" has the maximum sum");
System.out.print("Row "+index+" has the following values: ");
for(int i = 0; i < scores[index].length; i++){
System.out.print(scores[index][i] + " ");
}
}
}

How to reverse a triangle jagged array?

I have already done with normal jagged array, but I don't understand how to reverse it upside down. Also I have a question, how to shift the side of triangle from left side to right? Can I do this with loops or I need to write different quantity of whitespaces for every line of my array?
static int[][] triangle(int lines){
int[][] arr = new int[lines][];
for(int i = 0; i < arr.length; i++){
arr[i] = new int[i + 1];
}
int count = 0;
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
arr[i][j] = count++;
}
}
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
Some kind of result:
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
You can quickly create a reversed triangle by changing the way you initialize your arr array.
static int[][] revTriangle(int lines) {
int[][] arr = new int[lines][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[lines - i]; // this line
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++;
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
I get the following output:
0 1 2 3 4
5 6 7 8
9 10 11
12 13
14
Hope this helps!
If you need a more compact solution you can group some loops (basing on anacron answer):
static int[][] triangle( int lines, boolean straight)
{
int[][] arr = new int[lines][];
int count = 0;
for ( int i = 0; i < arr.length; i++ )
{
int start = (straight? i : lines);
int step = (straight? 1 : -i);
arr[i] = new int[start + step ];
for ( int j = 0; j < arr[i].length; j++ )
{
arr[i][j] = count++;
System.out.print( arr[i][j] + " " );
}
System.out.println();
}
return arr;
}

Switching rows on 2d-array generated at random

This is a 2d array which is generated at random, and stores 20 integers from 100-1000. I got that part right, I'm trying to switch the rows of this 2d array and not having much luck, i tried the temp but for some reason it comes out as column array...
public static void main (String args[]){
int [][] randArray = new int[2][10];
Random rnd = new Random();
for(int i=0; i<randArray.length; i++)
for(int j=0; j<randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i=0; i < randArray.length; i++){
System.out.println("Row " + i);
for (int j=0; j < randArray[i].length; j++)
System.out.print(randArray[i][j]+ " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j=0; j < randArray[0].length; j++){
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " ");
}
}
}
Switch the rows as in row1 [1,2,3,4,5] row2 [6,7,8,9,10] to row1[6,7,8,9,10] row2[1,2,3,4,5]
You can use Arrays.deepToString(Object[]) to print the array. Display the array after you perform your swap. Something like,
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++) {
for (int j = 0; j < randArray[i].length; j++) {
randArray[i][j] = 100 + rnd.nextInt(900);
}
}
System.out.println(Arrays.deepToString(randArray));
System.out.println("Switch row ");
for (int j = 0; j < randArray[0].length; j++) {
int temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
}
System.out.println(Arrays.deepToString(randArray));
Your code is working actually I fixed only the compile error;
public static void main(String args[]) {
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++)
for (int j = 0; j < randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j = 0; j < randArray[0].length; j++) {
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " "); no i variable
}
//I added only below lines to print your result
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
}

Finding the largest row and column, solution is inconsistent

Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.

Cannot get the addition to output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Categories

Resources