Filling a vertical matrix Java - java

I'm trying to fill a matrix vertically, but 1 row is missing. Can you help me ? There is the code. Maybe there is an easier way to fill a matrix verically, but i cant find it.
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}
Output:
Enter the value of matrix: 4
1 5 9 13
2 6 10 14
3 7 11 15

Your row is missing because you never printed it in your first loop (the one that is initializing your first line) - you should have a row of 0 4 10 12 at the beginning. But you could do it much easier with only one nested loop.

Try
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
matrix[0][0]=0; //you have forgotten the first value
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
//initializing the first line
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
}
// re-loop to display but this time start with i=0
for(int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}

To fill a matrix vertically, you must loop through columns in the outer loop and through rows in the inner(nested) loop. For example:
for(int j = 0; j < matrix.length; j++) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][j] = /* The value you want to fill */;
.../* Other stuff you wanna do */
}
}

There is an easier way of doing this:
keep a variable like count and iterate the matrix on columns first then rows:
int count = 1; // or 0 if you start with 0
int[][] a = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
a[j][i] = count; // notice j first then i
count++;
}
After that you can easly print out the values:
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
System.out.println(a[i][j]);

Related

How to find the amount of odd numbers and thee sum of all odd numbers in a inputted 2D array java?

I'm trying to find the total amount of odd numbers in a 2D array inputted by the user in java. I'm also trying to find the sum of all those odd numbers. I've figured out how to find the number of odd numbers in a strictly square 2d array (ie. 2x2, 3x3, 4x4, etc) but when I input an array size of for example 2x3 or say 5x6 the output is incorrect. What am I doing wrong?
import java.util.Scanner;
public class SumOfOdd
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
System.out.println("No. of rows");
int rows = input.nextInt();
System.out.println("No. of columns");
int cols = input.nextInt();
int [][] array1 = new int[rows][cols];
System.out.println("Input array elements");
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < cols; col++)
{
array1[row][col] = input.nextInt();
}
}
int count = 0;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++)
{
if(array1[i][j] % 2 == 1)
{
count++;
}
}
}
System.out.println("Odd number count = " + count);
}
}
Replace
for(int j = 0; j < array1.length; j++)
with
for(int j = 0; j < array1[i].length; j++)
Replace the nested for loop in the end
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++){
with
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{

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
        }
    

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);
}

Multiplying Muti-Dimensional Arrays

Been having a bit of trouble finishing this program involving two 2D arrays and multiplying them together. Now I was able to construct these arrays with set lengths and then using a number generator to create each array. As for a third array I was able to establish the length of the array, but when placing the three arrays into a method I am still having out of bounds issues.
public class arrayTest1{
public static void main ( String [] args){
int matrix1[][] = new int [5][2];
for (int i = 0; i < matrix1.length; i++)
for (int j = 0; j < matrix1[i].length; j++)
matrix1[i][j] = (int)(Math.random() * 1000);
System.out.println("The array 1 is: ");
for (int i = 0; i < matrix1.length; i++){
for (int j = 0; j < matrix1[i].length; j++){
System.out.print(matrix1[i][j]+" ");
}
System.out.println();
}
int matrix2[][] = new int [2][5];
for (int i = 0; i < matrix2.length; i++)
for (int j = 0; j < matrix2[i].length; j++)
matrix2[i][j] = (int)(Math.random() * 1000);
System.out.println("The array 2 is: ");
for (int i = 0; i < matrix2.length; i++){
for (int j = 0; j < matrix2[i].length; j++){
System.out.print(matrix2[i][j]+" ");
}
System.out.println();
}
int matrixSum[][] = new int [matrix1.length][matrix2[0].length];
matrixMulti(matrix1,matrix2,matrixSum);
System.out.println("The array mutliplied is: ");
for (int i = 0; i < matrixSum.length; i++){
for (int j = 0; j < matrixSum[i].length; j++){
System.out.print(matrixSum[i][j]+" ");
}
System.out.println();
}
}
public static void matrixMutli(int [][] m1, int [][] m2,int [][] totalMatrix){
for(int i = 0; i < m1.length; i++)
for(int j = 0; j < m2[0].length; j++)
for(int k = 0; k < totalMatrix.length; k++)
totalMatrix [i][j] += m1[i][k] * m2[k][j];
}
}
The ArrayIndexOutOfBounds is caused by the fact that your k variable goes from 0 to 5. It needs to go from 0 to 2. The problem is because of the line :
for(int k = 0; k < totalMatrix.length; k++)
The matrix totalMatrix is initialized with int matrixSum[][] = new int [matrix1.length][matrix2[0].length]; and matrix1.length is 5. So totalMatrix.length is 5.
To correct this you need to make sure that k is bounded by either matrix1[i].length or by matrix2.length. These two values need to be the same and you can choose either to be the bound for k.
So this is the code:
for(int i = 0; i < m1.length; i++)
for(int j = 0; j < m2[0].length; j++)
for(int k = 0; k < m2.length; k++)
totalMatrix [i][j] += m1[i][k] * m2[k][j];
Also consider adding code that checks whether m1[i].length == m2.length and throws an IllegalArgumentException if not. If you are still in trouble have a look at matrix multiplication.

Categories