Array

Know everything about Array in data structure kotlin now

An Array is a collection of similar data type stored at contiguous memory locations. It is a Linear Data Structure. By a linear array, we mean a list of a finite number n of similar data elements referenced respectively by a set of consecutive numbers, usually 1, 2, 3, …. n.

Types of Array :-

  • Single Dimensional Array
  • Two Dimensional Array

Single Dimensional Array

Syntax
val num = arrayOf(1, 2, 3, 4) //implicitly type declaration of type
val num = arrayOf<Int>(1, 2, 3) //explicitly type declaration of type

Example of Single Dimensional Array

class SingleDimensionalArray{  
fun main(args: Array<String>) {
    val a = IntArray(5) //declaration and instantiation  
    a[0] = 10 //initialization  
    a[1] = 20
    a[2] = 70
    a[3] = 40
    a[4] = 50
    //traversing array  
    for (i in a.indices)  //length is the property of array  
        println(a[i])
}
}
Output:
10
20
70
40
50

array

Two Dimensional Array

In two dimensional array, data is stored in row and column based index (also known as matrix form) or it is a collection of 1D array.

Syntax
val array = arrayOf(
    arrayOf(1, 2, 3),
    arrayOf(4, 5, 6),
    arrayOf(7, 8, 9)
)

Example of Two Dimensional Array

class TwodimensionaArray{  
fun main(args: Array<String>) {
//declaring and initializing 2D array  
val arr = arrayOf(intArrayOf(1, 2, 3), intArrayOf(2, 4, 5),         intArrayOf(4, 4, 5))
    //printing 2D array  
    for (i in 0..2) {
        for (j in 0..2) {
            print(arr[i][j].toString() + " ")
        }
        println()
    }
}
} 
Output:

1 2 3
2 4 5
4 4 5

Operations in Arrays

Following are the basic operations supported by an array.

  • Traverse − print all the array elements one by one.
  • Insertion − Adds an element at the given index.
  • Deletion − Deletes an element at the given index.
  • Search − Searches an element using the given index or by the value.
  • Update − Updates an element at the given index.

Properties of the Array

  • Each element of same data type and has a same size i.e. int = 4 bytes.
  • An index of array is always less than the total number of array items.
  • Elements are stored at contiguous memory locations.
  • You can Random access variable in array(in fixed size array).
  • it is Easy sorting and iteration.
  • Replacement of multiple variables

Disadvantages

  • Arrays are always fixed in size a user can not increase and decrease the length of the array according to their requirement or at run time.
  • Arrays can store only similar type of data.
  • Array can not provide readymade methods for user requirement such as sorting and searching

Hope this article suffices what you need to learn about. Check out my blog for more such posts.

Thanks!

Codinglance

You may also like...

0 Comments

No Comment.