0
0
Kotlinprogramming

Array creation and usage in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Kotlin
fun main() {
  val numbers = arrayOf(10, 20, 30)
  println(numbers[1])
  numbers[2] = 40
  println(numbers.joinToString())
}
This code creates an array, prints the second element, changes the third element, then prints all elements.
Execution Table
StepActionArray StateOutput
1Create array with elements 10, 20, 30[10, 20, 30]
2Access element at index 1[10, 20, 30]20
3Modify element at index 2 to 40[10, 20, 40]
4Print all elements joined by comma[10, 20, 40]10, 20, 40
💡 Program ends after printing the final array state.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
numbersnull[10, 20, 30][10, 20, 40][10, 20, 40]
Key Moments - 3 Insights
Why does numbers[1] print 20 and not 10 or 30?
Because array indexing starts at 0, numbers[1] accesses the second element, which is 20 (see execution_table step 2).
What happens when we assign numbers[2] = 40?
The third element (index 2) changes from 30 to 40, updating the array state (see execution_table step 3).
Why do we use joinToString() to print the array?
Printing the array directly prints its contents like '[10, 20, 40]' with brackets; joinToString() creates a readable comma-separated string without brackets (see execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 2?
A30
B10
C20
D40
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the array change its third element?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Action' and 'Array State' columns in execution_table for the step where modification happens.
If we changed numbers[0] = 50 at step 3, what would be the final array?
A[10, 20, 40]
B[50, 20, 40]
C[50, 20, 30]
D[10, 20, 30]
💡 Hint
Refer to variable_tracker and imagine changing the first element at step 3.
Concept Snapshot
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
Full Transcript
This example shows how to create an array in Kotlin using arrayOf with initial values. We access elements by their index starting at zero, so numbers[1] is the second element. We can change elements by assigning a new value to a specific index. Printing the array directly shows its contents with brackets like [10, 20, 40], so we use joinToString() to print elements clearly without brackets. The variable 'numbers' changes as we modify the array. The program ends after printing the final array.