Page 316 - Cs_withBlue_J_C11_Flipbook
P. 316
To create the above 2-dimensional array of 4 rows and 5 columns:
int array[ ][ ]=new int[4][5];
To refer to the positions in the array,
• If we want to print the value 44, we use
System.out.println(array[1][2])
• Similarly, if we want to access the position where 67 is kept, we use
array[3][1]=67;
Note: In both type of arrays, the subscript value starts from 0.
11.8.1 Inserting Values in a Double-Dimensional Array
Like single-dimensional arrays, in double-dimensional array values can be entered in four different ways. We can use
the static declaration method by using an assignment statement and the dynamic declaration method by using the
scanner class or input stream reader. The last method is taking input directly from the user during run time.
Let us see in detail.
Static way: By using Assignment Statements
In this method, the values are inserted by assigning them to arrays. This is like initializing values to the array. Some
examples have been shown below.
• int ar[ ][ ]={{1,2,3},{4,5,6},{6,7,8}};
• double ar[ ][ ] = {{1.2,3.4},{1.4,3.2}};
• char ar[ ][ ]={{'a','r'},{'1','4'},{',','='}};
• String ar[ ][ ]={{"India, "New Delhi"},{"America", "Washington, D.C"}};
Always remember to use single quotes with char type values and double quotes with strings.
Program 17 Write a program in Java to print marks of 16 students in matrix format.
1 class print_marks
2 {
3 public static void main()
4 {
5 int i, j;
6 int marks[ ][ ]={{67,87,89,79},{99,34,56,87},{45,87,69,80},{67,89,78,98}};
7 System.out.println ("Number of marks: "+ (marks.length*marks.length));
8 for(i=0; i<4; i++)
9 {
10 for(j=0; j<4; j++)
11 {
12 System.out.print (marks[i][j]+"\t");
13 }
314314 Touchpad Computer Science-XI

