Lesson: 22 – Arrays: concepts in kotlin language

Lesson: 22 – Arrays: concepts in kotlin language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

Arrays: concepts in kotlin language. In this section, we will look at other types of variables that allow us to store a set of data in a single variable. We use variables of a different type for data storage (Int, Float, Double, Byte, Short, Long, Char, Boolean variables).

An array is a data structure that allows you to store a SET of data of the same type.
With a unique name, an arrangement is defined and by means of a subscript we make reference to each element of the same (component).

Topic: Arrays: concepts in kotlin language.

Problem 1

You want to save the salaries of 5 workers.
According to the known, we should define 5 variables if we want to have at some point the 5 salaries stored in memory.
Using an arrangement, it is only necessary to define a single name and access each element through the subscript.

Lesson: 22 - Arrays: concepts in kotlin language - Lesson: 22 - Arrays: concepts in kotlin language - Lesson: 22 - Arrays: concepts in kotlin language -

Topic: Arrays: concepts in kotlin language.

Project98 – Principal.kt

fun main (parameter: Array <String>) {
    val wages: IntArray
    wages = IntArray (5)
    // load your items by keyboard
    for (i in 0..4) {
        print ("Enter salary:")
        wages [i] = readLine () !!. ToInt ()
    }
    // printing of your elements
    for (i in 0..4) {
        println (wages [i])
    }
}

To declare an array of integers we define a variable of type IntArray:

    Val wages: IntArray

To create the array and reserve space for 5 components we must do:

    Wages = IntArray (5)

To access each component of the array we use the brackets and using a subscript we indicate which component we are processing:

    for (i in 0..4) {
        print ("Enter salary:")
        wages [i] = readLine () !!. toInt ()
    }

When “i” evaluates 0 we are loading the first component of the array.

The components begin to be numbered from zero and reach the size indicated less 1.

Once we load all its components we can print them one by one inside another for:

    For (i in 0..4) {
        Println (wages [i])
    }

If we want to know the size of an array after it has been created, we can access the size:

    Val wages: IntArray
    Wages = IntArray (5)
    Println (salary.size) // a 5

It is more common to create an array of integers in a single line with the syntax:

    Val wages = IntArray (5)

Topic: Arrays: concepts in kotlin language.

Acotaciones

The standard Kotlin library contains all the basic classes that are required to program with this package-organized language.

In the kotlin package, we can identify that the IntArray class is declared.

The other types of arrangements provided by Kotlin are:

ByteArray
ShortArray
LongArray
FloatArray
DoubleArray
BooleanArray
CharArray

There is no one to handle String, in the next concepts we will see how to work with this type of data.

Problem 2

Define an arrangement of 5 Float-type components representing the heights of 5 people.
Get the average of them. Count how many people are higher than average and how many are lower.

Project99 – Principal.kt

fun main (parameter: Array <String>) {
    val heights = FloatArray (5)
    var sum = 0f
    for (i in 0..heights.size-1) {
        print ("Enter Height:")
        heights [i] = readLine () !!. toFloat ()
        sum += heights [i]
    }
    val average  = sum / heights.size
    println ("Average height: $average")
    var high = 0
    var low  = 0
    for (i in 0..heights.size-1)
        if (heights[i] > average)
            high ++
        else
            low ++
    println ("Number of people higher than average: $high")
    println ("Number of people lower than average: $low")
}

We create an array with floating element data of 5 elements using the class FloatArray:

    Val heights = FloatArray (5)

In the first for we load each height and accumulate it in the variable sum. The variable sum is defined by Float inference if we add the character “f” or “F”:

    Var sum = 0f

Within the for we charge and accumulate:

    For (i in 0..alights.size-1) {
        Print ("Enter Height:")
        Heights [i] = readLine () !!. ToFloat ()
        Sum + = heights [i]
    }

Then when we leave the for we get the average height of the people and we show it:

    Average val = sum / heights.size
    Println ("Average height: $ average")

To count the number of people higher than the average and lower we must define two counters and within another to control each height with respect to the average:

    Var high = 0
    Low var = 0
    For (i in 0..alights.size-1)
        If (average heights [i]>)
            High ++
        Else
            Low ++

As the for has a single sentence are not mandatory keys.

Outside the for we show the two counters:

    Println ("Number of people higher than average: $ high")
    Println ("Number of people lower than average: low $")

Topic: Arrays: concepts in kotlin language.

Problem 3

Load an array of 10 integer elements and subsequently check if the array is sorted from least to largest.

Project100 – Home.kt

fun main (parameter: Array <String>) {
    val array = IntArray (10)
    for (i in 0..array.size-1) {
        print ("Enter item:")
        array[i] = readLine () !!. toInt ()
    }
    var sorted = true
    for (i in 0..array.size-2)
        if (array [i + 1] <array [i])
            sorted = false
    if (sorted)
        print ("Elements are ordered from lowest to highest")
    else
        print ("Elements are not sorted from least to largest")
}

We define an array of 10 elements of integer type and proceed to load it by keyboard:

    Val array = IntArray (10)
    For (i in 0..array.size-1) {
        Print ("Enter item:")
        Fix [i] = readLine () !!. ToInt ()
    }

We define a variable of type Boolean with the value true (assuming that the array is ordered from least to largest before analyzing it.

    Var sorted = true

By inference the compiler knows that the ordered variable must be of type Boolean, the other way to define is:

    Var sorted: Boolean = true

Now by another “for” we proceed to compare an element of the position i + 1 with that of the position i, if it is met that is greater we can already infer that the array is not ordered:

    For (i in 0..array.size-2)
        If (array [i + 1] <array [i])
            Ordered = false

Out of the for we ask for the content of the variable “ordered” if it has stored the value true means that the vector is ordered from minor to major:

    If (ordered)
        Print ("Elements are ordered from lowest to highest")
    Else
        Print ("Elements are not sorted from least to largest")

If we want to make a little more efficient the verification of if the array is ordered we can cut the comparisons as soon as an unordered element appears through the keyword break:

    For (i in 0..array.size-2)
        If (array [i + 1] <array [i]) {
            Ordered = false
            Break
        }

The break command comes out of the repetitive structure containing it immediately without continuing the cycle.

Topic: Arrays: concepts in kotlin language.

Property indices of classes IntArray, ByteArray, LongArray etc.

The IntArray class has an IntRange property named indexes that stores the minimum and maximum range of the array.
The property indices we can use it in the for to traverse the components:

Problem 4

Load an array of 10 integer elements. Then print the first and last element.

Project101 – Principal.kt

fun main (parameter: Array <String>) {
    val array = IntArray (10)
    for (i in array.indices) {
        print ("Enter item:")
        array[i] = readLine () !!. toInt ()
    }
    println ("First component of array ${array [0]}")
    println ("Last fix component ${array [array.lastIndex]}")
}

It is more convenient to use the index property instead of having the range: 0..artable.size-1 if we are going to go through the entire array.

To access the last component of the array we use the lastIndex property that returns the last valid index:

    Println ("Last fix component ${array [fix.lastIndex]}")

Iterate with a for an array object

In addition to the way, we have seen to access the elements of an array using a subscript we can use the “for”  looping structure with iterators.

Problem 5

Load an array of 5 integer elements. Then print the whole arrangement.

Project102 – Principal.kt

fun main (parameter: Array <String>) {
    val array = IntArray (10)
    for (i in array.indices) {
        print ("Enter item:")
        array[i] = readLine () !!. toInt ()
    }
    for (element in array)
        println (element)
}

To iterate a complete array with a for we use the following syntax:

    For (element in array)
        Println (element)

Each turn of the for is stored in the variable element a value stored in the variable “fix”.

As we see is a very simple syntax to go through an array and access each element to consult.

Other features of the fixtures may be useful.

Print each element and its index by iterating the array by calling the intIndex method of the IntArray class:

    For ((index, element) in array.withIndex ())
        Println ("In index $ index the item $ element is stored")

Load elements using the for as iterator;

    For ((index, element) in array.withIndex ())
    {
        Print ("Enter item:")
        Fix [index] = readLine () !!. ToInt ()
    }

Problems proposed

  • Develop a program that allows entering an array of 8 integers, and report:
    The accumulated value of all elements.
    The accumulated value of the elements that are greater than 36.
    The quantity of values greater than 50.
    (Define two for, in the first to carry the load and in the second proceed to analyze each element)
  • Perform a program that requests the loading of two integer numeric arrays of 4 elements. Obtain the sum of the two arrays element by element, said result to save it in a third arrangement of the same size.
Project103
fun main (parameter: Array <String>) {
    val array = IntArray (8)
    for (i in array.indices) {
        print ("Enter item:")
        array[i] = readLine () !!. toInt ()
    }
    var sum = 0
    var sumMayor36 = 0
    var cantMayor50 = 0
    for (element in array) {
        sum += element
                if (element> 30)
                    sumMayor36 += element
                            if (element > 50)
                                cantMayor50 ++
    }
    println ("Cumulative value of the array: $sum")
    println ("Cumulative value of items greater than 36: $sumMayor36")
    println ("Number of items greater than 50: $cantMayor50")
}


fun main (parameter: Array <String>) {
    val array1 = IntArray (4)
    val array2 = IntArray (4)
    println ("Load the first fix")
    for (i in array1.indices) {
        print ("Enter item:")
        array1[i] = readLine () !!. toInt ()
    }
    println ("Loading the Second Arrangement")
    for (i in array2.indices) {
        print ("Enter item:")
        array2[i] = readLine () !!. toInt ()
    }
    val arraySum = IntArray (4)
    for (i in arraySum.indices)

        arraySum[i] = array1[i] + array2[i]

            println ("Resulting Arrangement")

        for (element in arraySum)
            println (element)
}

 

About The Author

Related posts

Leave a Reply