Monday, May 9, 2022

[FIXED] How to create a Java matrix that consists of numbers that are the product of 2?

Issue

I'm trying to create a 2D int array of numbers that are the product of 2 via user input defining the length of the rows and columns, as the one below:

1 2 4 8

2 4 8 16

4 8 16 32

8 16 32 64

I've only got up to here, and cannot figure out how to make the matrix to start from 1 and to look like the one above. I'd appreciate your help on this one!

    Scanner scan = new Scanner(System.in);
    int n = Integer.parseInt(scan.nextLine());

    int[][] matrix = new int[n][n];

    matrix[0][0] = 1;
    int temp = 1;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            matrix[i][j] = temp * 2;
            temp *= 2;
        }
    }

    System.out.println(Arrays.deepToString(matrix));

Solution

I'd say that each element of the matrix would be:

matrix[i][j] = (int) Math.pow(2, i+j) ;

So, your loop would look like this:

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


Answered By - Mario MG
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.