Ranges


Ranges

In Kotlin, the range is a collection of finite values defined by endpoints. Kotlin's ranges consist of a beginning, a stop, and a step. The start and stop range are included, and the value of the step is the default1. The range is also used with similar types.

There are three ways to create ranges:

  1. (..) is used by the operator
  2. Using the rangeTo () function
  3. Using the downTo () function

  1. (..) is used by the operator – This is the simplest way to work in range. This will create a range from start to finish, including start and end values. This is the rangeTo () function (..). We can create an array of integers and characters using the operator. (..) is used by the operator
  2. rangeTo () function is similar to the (..) operator. This will create a range up to the value given as an argument. It is also used to create arrays for integers and characters. Using the rangeTo () function
  3. downTo () function – This is the opposite of rangeTo() or (..) operator. This creates an ascending array, i.e., from the largest to the smallest value. We create arrays in reverse order for integers and characters.

The range used for forEach loop - The forEach loop is used to move through the range.

Step ()

Using the keyword step, we can enter a step between the values. It is mainly used to fill in the gaps between two values in the RangeTo () or downTo () or in (..) operator. The default value of the step is 1, and the value of the step function should not be 0.

Reverse function ()

It is used to inverse a given range type. Instead of downTo (), we can use the reverse () function to print the array in descending order.

Pre-defined functions - There are some pre-defined functions in range. They are max (), min (), average () and sum ().