In: Computer Science
few problems example of array and 2d array and the solution code in java language. I am new to java and trying to learn this chapter and it is kinda hard for me to understand.
Java program for 1d and 2d array :-
public class MyClass {
public static void main(String args[]) {
int arr[] = new int[5]; //creating an array of 5 elements
//how to define elements of the array
arr[0]=5;
arr[1]=6;
arr[2]=7;
arr[3]=8;
arr[4]=9;
//printing elements of the array
for(int i=0;i<5;i++)
{
System.out.print(arr[i]+" ");
}
//creating new 2d aray
int arr_d[][] = new int[2][2]; //creating 2d matrix or 2d
array
//accessing i and j columns
arr_d[0][0] = 2;
arr_d[0][1] = 3;
arr_d[1][0] = 4;
arr_d[1][1] = 5;
System.out.println();
System.out.println();
System.out.println("The 2d array :");
//printing 2d matrix
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(arr_d[i][j]+" ");
}
System.out.println();
}
}
}
Output:-