'setting all values in a 2d array to a specific value

I am trying to create a method that will take inputs of row column and value to then create a 2d array with the specified dimensions and the input value as the value in every spot in the array. This is what I have come up with

  public static int[][] makeArray(int r, int c, int v) {
    int[][] arr = new int[r][c];
    for (int i = 0; i <= c; i++) {
      for (int j = 0; j <= r; j++) {
        arr[i][j] = v;
      }
    }
    return arr;
  }

However I seem to be getting this error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10

Could someone help me with this



Solution 1:[1]

Arrays indices starts from 0, so if your array's length is 10 it means that max index (or the index of last element) is 9.

Solution:

  public static int[][] makeArray(int r, int c, int v) {
    int[][] arr = new int[r][c];
    for (int i = 0; i < c; i++) {
      for (int j = 0; j < r; j++) {
        arr[i][j] = v;
      }
    }
    return arr;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ulou