Single and Multidimensional array


In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called a one-dimensional array. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched. Many time programmers need a way to store many variables of the same category or same type, so arrays can be used to store all these variables with a single variable name which is the name of the array. For example, if a programmer wants to store months of the year like January, February and so on, rather than creating different variables for each month he/she can create an Array named months and store names of all months in it.

Array in Java:

In Java, arrays are homogeneous data structures implemented in Java as objects. An array can conta in primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment.

There are Two types of array in Java:



1.    Single Dimensional Array.

2.    Multidimensional Array.

Single Dimensional arrays

A one-dimensional array (or single dimension array) is a type of linear array. Accessing its elements involves a single subscript which can either represent a row or column index.

As an example consider the C declaration int anArrayName[10]; which declares a one-dimensional array of ten integers. Here, the array can store ten elements of type int . This array has indices starting from zero through nine. For example, the expressions anArrayName[0] and anArrayName[9] are the first and last elements respectively.

For a vector with linear addressing, the element with index i is located at the address B + c × i, where B is a fixed base address and c a fixed constant, sometimes called the address increment or stride.

If the valid element indices begin at 0, the constant B is simply the address of the first element of the array. For this reason, the C programming language specifies that array indexes always begin at 0; and many programmers will call that element "zeroth" rather than "first".

However, one can choose the index of the first element by an appropriate choice of the base address B. For example, if the array has five elements, indexed 1 through 5, and the base address B is replaced by B + 30c, then the indices of those same elements will be 31 to 35. If the numbering does not start at 0, the constant B may not be the address of any element.

Example:

            int number1 = num[0]

So, in the above example the variable number1 will be assigned the value of the 0th index element in an array of name num.

We can also assign a new value to any element in the array using its index. The data type of the new value must be the same as the data type of other elements. In the below example the value at 2nd index of array num is changed to 40.

Example:

            num[2] = 40;

Below code snippets show everything mentioned above.

public static void main(String args[]) {

   int month_days[];  

    // initializing a new array of size 12.

    month_days = new int[12];

    // Assigning values to each index     

    month_days[0] = 31;

    month_days[1] = 28;

    month_days[2] = 31;

    month_days[3] = 30;

    month_days[4] = 31;

    month_days[5] = 30;

    month_days[6] = 31;

    month_days[8] = 30;

    month_days[9] = 31;

    month_days[10] = 30;

    month_days[11] = 31;

    // Accessing value at some index (3 in this case)

     System.out.println("April has " + month_days[3] + " days.");

     }

}

Accessing or assigning the values of array using For loop:

As all elements in the array can be accessed via its index. So, to access or assign values of array for loop can be used. By looping through all the indices of the array we can change or access the element at that index.

The Below code snippets shows how to use for loop on array:

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

  System.out.println("Element at index " + i +

                                " : "+ arr[i]);

// assigning the values to elements

for (int i = 0; i < arr.length; i++)

  // values at each index is 10 times the said index

  arr[i] = i * 10;

 

Notes:

1.    The elements in the array allocated by new will automatically initialize to zero (for numeric type) , false (for Boolean) , or null (for objects).

2.    When one tries to access index elements outside the array size the JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.

 Multidimensional array

For a multidimensional array, the element with indices i,j would have address B + c · i + d · j, where the coefficients c and d are the row and column address increments, respectively.

More generally, in a k-dimensional array, the address of an element with indices i1, i2, ..., ik is

B + c1 · i1 + c2 · i2 + … + ck · ik.

For example: int a[2][3];

This means that array a has 2 rows and 3 columns, and the array is of integer type. Here we can store 6 elements. They will be stored linearly but starting from the first row linear then continuing with the second row. The above array will be stored as a11, a12, a13, a21, a22, a23.

This formula requires only k multiplications and k additions, for any array that can fit in memory. Moreover, if any coefficient is a fixed power of 2, the multiplication can be replaced by bit shifting.

The coefficients ck must be chosen so that every valid index tuple maps to the address of a distinct element.

If the minimum legal value for every index is 0, then B is the address of the element whose indices are all zero. As in the one-dimensional case, the element indices may be changed by changing the base address B. Thus, if a two-dimensional array has rows and columns indexed from 1 to 10 and 1 to 20, respectively, then replacing B by B + c1 − 3c2 will cause them to be renumbered from 0 through 9 and 4 through 23, respectively. Taking advantage of this feature, some languages specify that array indices begin at 1, as in mathematical tradition while other languages (like Fortran 90, Pascal and Algol) let the user choose the minimum value for each index.

Accessing and assigning values in multidimensional array:

Similar to the 1-d array, elements in a multidimensional array can be accessed using indices. Nested for loops can be used to loop through all indices and assign or access the elements as shown in below code snippet.

class Mul2D{

 public static void main(String args[]) {

 

     // Declaring the array

     int mul2d[][]= new int[4][5];

     int i, j, k = 0;

    

     // Assigning the values

     // looping through the rows

     for(i=0; i<4; i++)

 

      // looping through the columns

       for(j=0; j<5; j++) {

       Mul2D[i][j] = k;

       k++;

     }

     //./fgdfd6

    for(i=0; i<4; i++) {

       for(j=0; j<5; j++);

          System.out.print(mul2d[i][j] + " ");

          System.out.println();

       }

   }

}

 

Passing array to methods:

Like variables , we can also pass arrays to methods. For example the below program passes the array to method display to display the first three elements of that array in the console.

public class PMethods{

public static void display(int y[])

     {

             System.out.println(y[0]);

             System.out.println(y[1]);

             System.out.println(y[2]);

     }

public static void main(String args[])

     {

     int x[] = { 1, 2, 3 };

     display(x);

     }

}

 

References:

1.https://www.geeksforgeeks.org/arrays-in-java/?ref=lbp

2.https://www.geeksforgeeks.org/multidimensional-arrays-in-java/?ref=lbp

3.https://www.javatpoint.com/array-in-java

4.https://www.w3schools.com/java/java_arrays.asp

5.https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html


Comments

Post a Comment