Nikoa
Nikoa

Reputation: 13

How to define elements in matrix in Java, where in every next row elements increase for some value?

For example I want to make this kind of matrix:

1  1  1  1  1  1
4  4  4  4  4  4
9  9  9  9  9  9
16 16 16 16 16 16 
25 25 25 25 25 25 
36 36 36 36 36 36
49 49 49 49 49 49

My code so far:

public static void main(String[] args) {

        int matrix[][] = new int[6][8];

        for (int i = 0; i < matrix.length; ++i) {
            for (int j = 0; j < matrix.length; j++) {

                matrix[i][j] = i + 1 ;
            }

        }

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }

    }
}

Upvotes: 0

Views: 59

Answers (3)

just coding
just coding

Reputation: 193

You can use Java.lang.Math.pow() method. But since its only a sqaure function I dont see any harm in using matrix[i][j] = (i+1)*(i+1) ; , inject this code at your 8th line.

Upvotes: 0

Shanu Gupta
Shanu Gupta

Reputation: 3807

If you look closely, each element in your result matrix is square of the row number.

Eg.

Row 1 -> Numbers 1
Row 2 -> Numbers 4
Row 3 -> Numbers 9
...
Row 7 -> Numbers 49

and so on...

So you don't need the previous numbers to calculate the new ones.

A simple tweak in your existing code, while populating the matrix, would work:

for (int i = 0; i < matrix.length; ++i) {
    for (int j = 0; j < matrix[0].length; j++) {
        matrix[i][j] = (int) Math.pow(i + 1, 2);
    }
}

And print the matrix using :

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[0].length; j++) {
        System.out.print(matrix[i][j] + "\t");
    }
    System.out.println();
}

Upvotes: 1

Avvappa Hegadyal
Avvappa Hegadyal

Reputation: 273

public class Matrix {
 public static void main(String[] args) {
int matrix[][] = new int[7][8];
for (int i = 0; i < matrix.length; ++i) {
    for (int j = 0; j < matrix.length; j++) {
        matrix[i][j] = i + 1 ;
    }
}
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix.length; j++) {
        //Change this line,looking for this?
        System.out.print(matrix[i][j]*matrix[i][j] + "\t");
       //Describe your specific problem properly
    }
    System.out.println();
}}

Upvotes: 0

Related Questions