[Kotlin] for문, while문

이도연·2023년 12월 19일
0

기초 문법

목록 보기
7/10



for

val pets = arrayOf("dog", "cat", "canary")
for (element in pets) {
    print(element + " ")
}
⇒ dog cat canary
val pets = arrayOf("dog", "cat", "canary")
for ((index, element) in pets.withIndex()) {
    println("Item at $index is $element\n")
}
⇒ Item at 0 is dog
Item at 1 is cat
Item at 2 is canary

withIndex 를 통해 번호와 데이터를 같이 얻을 수 있다.
for 문으로 pets 을 순회하며 index 에 번호, element 에 값을 할당한다.


while

var bicycles = 0
while (bicycles < 50) {
    bicycles++
}
println("$bicycles bicycles in the bicycle rack\n")50 bicycles in the bicycle rack
var bicycle = 50
do {
    bicycles--
} while (bicycles > 50)
println("$bicycles bicycles in the bicycle rack\n")49 bicycles in the bicycle rack

반복 루프

repeat(2) {
     print("Hello!")
}
⇒ Hello!Hello!

Kotlin 에는 중괄호 안에 이어지는 코드 블록을 반복할 수 있는 반복 루프가 있다.
괄호 안의 숫자는 반복해야 하는 횟수이다.


출처 링크텍스트

0개의 댓글