PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

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

 May 09, 2022     java, matrix, product     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing