Kotlin/Kotlin 입문

[Kotlin] 5. 반복문

JoonYong 2024. 10. 9. 16:23

1. 반복문의 필요성

반복문은 똑같은 내용을 계속해서 출력하거나 규칙이 있는 같은 동작을 반복해야 하는 경우에 사용하여 코드를 효율적으로 작성할 수 있습니다.

fun main() {
    println("Hello World!")
    println("Hello World!")
    println("Hello World!")
}
fun main() {
    var total = 0
    total += 1
    total += 2
    total += 3
    println("total=$total")
}

2. 반복문의 종류

반복문은 특정 로직을 반복 실행할 때 사용합니다. 코틀린(Kotlin)에서는 forwhile을 제공합니다.

for 문

  • 시작 index부터 마지막 index까지 값을 증가시키면서 블록을 실행합니다.
fun main() {
    for (index: Int in 1..10) {
        println("index=$index")
    }
    for (index: Int in 1 until 10) {
        println("index=$index")
    }
    for (index: Int in 1..10 step 2) {
        println("index=$index")
    }
    for (index: Int in 10 downTo 1) {
        println("index=$index")
    }
    for (index: Int in 10 downTo 1 step 2) {
        println("index=$index")
    }
}

while 문

  • 조건이 거짓이 될 때까지 코드 블록을 반복 실행합니다.
fun main() {
    var count = 0
    while (count <= 10) {
        println("count=$count")
        count++
    }
    count = 10
    while (count >= 0) {
        println("count=$count")
        count--
    }
}

3. 제어문 (break, continue)

  • break: 반복문을 즉시 종료합니다.
  • continue: 현재 반복을 건너뛰고 다음 반복을 계속합니다.
fun main() {
    var count = 0
    while (count <= 10) {
        if (count == 5) {
            break
        }
        println("count=$count")
        count++
    }
    for (index: Int in 0..10) {
        if (index == 5) {
            continue
        }
        println("index=$index")
    }
}

4. 이중 반복문

  • 반복문 내에 또 다른 반복문을 사용할 수 있습니다.
fun main() {
    for (outIndex in 0..3) {
        println("outIndex 시작=$outIndex")
        for (inIndex in 0..3) {
            println("    inIndex=$inIndex")
        }
        println("outIndex 종료=$outIndex")
    }
}