简体   繁体   中英

Assigning values to a 2D array using a nested for loop

I want to iterate values to my 2D array by using a nested for loop but here is what I have so far. I think it does populate my 2D array but not with the numbers I want. I want it to populate with the powers of 2 starting at 2. So my outcome would look like: 2, 4, 8, 16, 32, 64.. and so on until my rows and columns are complete.

My code:

public class RowsSum {
    public static void main(String[] args) {
        int[][] nums = new int[5][3]; //declaring a 2D array of type int
        for (int i = 0; i <= nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                nums[i][j] = (i * nums[0].length) + j + 1;
                System.out.print(nums[i][j] + "\t");
            }//closing inner loop
            System.out.println("");
        }// closing nested for loop
    }// closing main method
}//closing class

This should work:

public class RowsSum {
  public static void main(String[] args) {
    int[][] nums = new int[5][3]; //declaring a 2D array of type int
    int num = 2;
    for (int i = 0; i < nums.length; i++) {
      for (int j = 0; j < nums[i].length; j++) {
        nums[i][j] = (int) Math.pow(num, ((i*nums[i].length)+j+1)); //code A
        System.out.print(nums[i][j] + "\t");
      }//closing inner loop
      System.out.println("");
    }// closing nested for loop
  }// closing main method
}//closing class

Code A: Here, I just set the value inside the array to 2 to the power of the position in the array, starting from 1. To get the position, I multiply the current col index by the length of each row plus the index in the current row. This is just a way to do it without creating a new count variable outside the loop and then incrementing it every time in the inner loop, although you could do that too if you want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM