08 Arrays

8.1 | Arrays

An array is a data structure that stores a collection of values of the same data type. Values stored in the array are accessible through the array index

//Declaring an array of integers

int arr1[];


//Creating an integer array with values

int[] arr0 = {2,3,4,5,6,7};


//Creating an integer array which can hold 100 integers

int arr2[] = new int[100];

//Or,

int arraySize = 100;

int arr3[] = new int[arraySize];


//Assigning values to the array

arr3[0] = 1;
arr3[1] = 2;


//Creating a string array which can hold 100 values

String arr4[] = new String[100];


//Assigning values to the array

arr4[0] = "This";
arr4[1] = "is a string array by";
arr4[2] = "testinganswers.com";


//Accessing array values by using for loop

for(int i=0;i<arr3.length; i++){
     System.out.println("arr3["+i+"] = "+arr3[i]);
}

//Or by using for each loop,

for(int element:arr3){

    System.out.println(element +",");

}

//Copying array

int[] arr5 = arr3;
String[] arr6 = arr4;





8.1.1 | Multi-dimensional Arrays

Multi-dimensional arrays are arrays of an array. They use more than one index to store and access values.

//Declaring a multi-dimensional array

int[][] arr0;


//Creating a multi-dimensional array

int[][] arr1 = {
                       {1,2,3}
                       {4,5,6}
                       {7,8,9}
                    };



//Creating a multi-dimensional array of size 2*3
int[][] arr2 = new int[2][3];


//Creating a multi-dimensional array using variables

int arrayXsize = 3;
int arrayYsize = 3;
int[][] arr3 = new int[arrayXsize][arrayYsize];



//Assigning values to multi-dimensional arrays

arr3[0][0] = 1;
arr3[0][2] = 3;


//Accessing values from multi-dimensional arrays

for(int i=0;i<arr2.length;i++){
    for(int j=0;j<arr2[i].length;j++){
         System.out.println("arr2["+i+"]["+j+"] = "+arr2[i][j]);
    }
}


//Copying multi-dimensional arrays

int[][] arr4 = arr3;


No comments: