PHpullh
학습 라이브러리/Kotlin/반복문 — for, while, repeat

KOTLIN · 기초 문법

반복문 — for, while, repeat

Range, withIndex, until, downTo, step 등 Kotlin 반복문의 모든 패턴을 익힙니다.

기초 문법입문forwhilerangeuntildownTo

핵심 설명

Range, withIndex, until, downTo, step 등 Kotlin 반복문의 모든 패턴을 익힙니다.

Kotlin code

// 닫힌 범위 1..5 (5 포함)
for (i in 1..5) print("$i ")          // 1 2 3 4 5

// 열린 범위 until (5 미포함)
for (i in 1 until 5) print("$i ")     // 1 2 3 4

// 역순
for (i in 5 downTo 1) print("$i ")   // 5 4 3 2 1

// 스텝
for (i in 0..10 step 2) print("$i ") // 0 2 4 6 8 10

// 컬렉션 순회
val fruits = listOf("🍎", "🍌", "🍇")
for (fruit in fruits) println(fruit)

// 인덱스와 값 동시에
for ((idx, fruit) in fruits.withIndex()) {
    println("$idx: $fruit")
}

// while
var n = 5
while (n > 0) { print("$n "); n-- }

// repeat
repeat(3) { i -> println("반복 $i") }

학습 팁

forEach에서는 break/continue를 사용할 수 없습니다. 이 경우 for문이나 run { list.forEach { if(...) return@run } } 패턴을 사용하세요.

주의할 점

1..5는 5를 포함(closed range), 1 until 5는 5 미포함(half-open range)입니다. 배열 인덱스 순회 시 0 until arr.size 또는 arr.indices를 사용하세요.

자주 묻는 질문

반복문 — for, while, repeat란 무엇인가요?

Range, withIndex, until, downTo, step 등 Kotlin 반복문의 모든 패턴을 익힙니다.

반복문 — for, while, repeat 학습 시 주의할 점은 무엇인가요?

1..5 는 5를 포함(closed range), 1 until 5 는 5 미포함(half-open range)입니다. 배열 인덱스 순회 시 0 until arr.size 또는 arr.indices 를 사용하세요.