How to initialize a two dimensional array? Give example.
Question
How to initialize a two dimensional array? Give example.
Solution
To initialize a two-dimensional array, you can follow these steps:
-
Declare the array variable with the desired data type. For example, you can declare an integer two-dimensional array as follows:
int[][] array; -
Allocate memory for the array using the
newkeyword. Specify the size of the array in the square brackets. For example, to create a 3x3 integer array, you can use the following code:array = new int[3][3]; -
Initialize the elements of the array with the desired values. You can access individual elements using the row and column indices. For example, to set the value 10 to the element at row 0 and column 1, you can use the following code:
array[0][1] = 10;
Here's an example of initializing and accessing a two-dimensional array in Java:
public class TwoDimensionalArrayExample {
public static void main(String[] args) {
int[][] array = new int[3][3];
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
array[2][0] = 7;
array[2][1] = 8;
array[2][2] = 9;
System.out.println("Element at row 0 and column 1: " + array[0][1]);
}
}
This example initializes a 3x3 integer array and sets different values to its elements. It then prints the value at row 0 and column 1, which is 2 in this case.
Similar Questions
How do you initialize a 2D array in C?
Explain different ways in which you can declare and initialize a single dimensionalarray.
What is the correct way to declare and initialize a one-dimensional array in C?
How do you initialize the third element of a 1D array named 'array' to 5?
A multidimensional integer array is initialized in the code editor.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.