Concept Flow - Array creation and usage
Start
Create Array
Access Elements
Modify Elements
Use Array in Code
End
This flow shows how to create an array, access and modify its elements, then use it in your program.
fun main() { val numbers = arrayOf(10, 20, 30) println(numbers[1]) numbers[2] = 40 println(numbers.joinToString()) }
| Step | Action | Array State | Output |
|---|---|---|---|
| 1 | Create array with elements 10, 20, 30 | [10, 20, 30] | |
| 2 | Access element at index 1 | [10, 20, 30] | 20 |
| 3 | Modify element at index 2 to 40 | [10, 20, 40] | |
| 4 | Print all elements joined by comma | [10, 20, 40] | 10, 20, 40 |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| numbers | null | [10, 20, 30] | [10, 20, 40] | [10, 20, 40] |
Array creation: val arr = arrayOf(1, 2, 3) Access elements: arr[index], index starts at 0 Modify elements: arr[index] = newValue Use joinToString() to print array nicely Arrays hold fixed-size collections of items
arrayOf() to create an array with given elements.val arr = arrayOf(1, 2, 3) uses arrayOf(1, 2, 3) which is correct. val arr = [1, 2, 3] uses square brackets which is invalid in Kotlin. val arr = IntArray(1, 2, 3) which uses invalid constructor arguments for IntArray. val arr = Array(3) { 1, 2, 3 } tries to pass multiple values in a lambda which is incorrect.Array(size) { init } creates an array of given size, initializing each element with the lambda result.val arr = Array(5) { 0 } correctly uses Array(5) { 0 } to create an array of 5 zeros. val arr = Array(0, 0, 0, 0, 0) is invalid syntax. val arr = Array(5, 0) is invalid syntax. val arr = IntArray(5, 0) is invalid because IntArray constructor takes only size or size with init lambda, not two parameters.val arr = arrayOf(10, 20, 30) println(arr[1])
arr[0] is 10, arr[1] is 20, and arr[2] is 30.arr[1], which is 20.val arr = arrayOf(1, 2, 3) arr[3] = 4 println(arr.joinToString())
arr[3] = 4 causes an IndexOutOfBoundsException at runtime.Array(size) { index -> value } creates an array where each element is initialized by the lambda using the index.val arr = Array(4) { index -> index * index } uses explicit lambda parameter index and correctly computes index squared. val arr = arrayOf(4) { index -> index * index } is invalid because arrayOf does not take a size and lambda. val arr = intArrayOf(4) { index -> index * index } is invalid syntax for the intArrayOf factory function. val arr = Array(4) { -> it * it } has invalid lambda syntax where it is undefined.Pass the test and this pattern moves unknown