0
fun main() {
    var brojevi: ArrayInt = arrayOf(1,2,3,4,5)
        
    for(i in 1..10)
    brojevi.add([i])
        
    println(brojevi)    
}  

how to add numbers from 1 to 10 in brojevi variable

1
  • if I wasnt trying I wouldnt be here Commented Jun 17, 2021 at 17:53

2 Answers 2

1

The arrays in Kotlin are fixed-size. That means once created, we can’t resize them. To get a resizable-array implementation, consider using MutableList instead, which can grow or shrink automatically as needed.

However, if you’re stuck on using arrays, you can create a new array to accommodate the additional element.

The trick is to convert the array into a MutableList, add the specified element at the end of the list, and finally return an array containing all the elements in this list.

Try this

fun main() {
    var brojevi: Array<Int> = arrayOf(1,2,3,4,5)
    var tempList: MutableList<Int> = brojevi.toMutableList()

    for(i in 1..10) {
        tempList.add(i)
    }

    var resultArray = tempList.toTypedArray()
    println(resultArray.contentToString())

}

Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot you saved me! Have a nice day!
If my answer solved your problem then you may mark that answer as accepted answer. Happy coding!
0

Check here how to use for loops in Kotlin https://kotlinlang.org/docs/control-flow.html#when-expression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.