본문 바로가기
kotlin/문법

[kotlin] loop (반복문) for, while, do while

by 코드 이야기 2020. 12. 30.
728x90

 

kotlinlang.org/docs/reference/control-flow.html#for-loops

 

Control Flow: if, when, for, while - Kotlin Programming Language

 

kotlinlang.org

kotlin 공식 홈페이지의 글을 정리해두었습니다.

 

 

와! 반복문!!

 

우선 이 두녀석부터 볼게요!

while & do while

이녀석은 우리가 알고있는 그 while, do while과 같습니다.

//while
fun main() {
    var x: Int = 5
    while (x > 0) {
        println(x)
        x--
    }
}
//do while
fun main() {
    var y: Int = 5
    do {
        println(y)
        y--
    } while (y > 0) 
}

평소에 알던 그 모양 고대로죠?

그럼 이제 for문을 봅시다.

 

 

for

for in문을 살펴보겠습니다.

//기본 for in문 | for(int i=1; i<=3; i++)
fun main() {
    for (i in 1..3) {
        println(i)
    }
}
//for(int i=6; i>=0; i-=2)
fun main() {
    for (i in 6 downTo 0 step 2) {
        println(i)
    }
}
// for(int i=0; i<arr.size(); i++) 
fun main() {
    val array: IntArray = intArrayOf(1, 2, 3, 4, 5)

    for (i in array.indices) {
        println(array[i])
    }
    //or

    for (item in array) {
        println(item)
    }
    //or
    for(i in 0 until array.size) {  //step이나 downTo을 이용하여 증감 크기를 바꿔줄 수 있음
        println(array.get(i))
    }
}

여기까지는 그렇다 치겠는데 조금 신기한 for문의 사용 방법이 있었는데요..!

 

 

 

forEach

array.forEach {
    println(it)
}
//or
array.forEach { n ->
    println(n)
}

 

//kotlin
fun main() {
    val array: IntArray = intArrayOf(1, 2, 3, 4, 5)
    
    array.forEachIndexed{index, value ->
        println("the element at $index is $value")
    }
    //or
    for ((index, value) in array.withIndex()) {
        println("the element at $index is $value")
    }
}

==

//c++
for(int i=0; i<arr.size(); i++) {
    int index = i;
    int value = arr[i];
    
    cout << "the element at " << index << " is " << value;
}

 

이 문법은 조금 신박하게 다가왔네요..! 

 

 

 

 

728x90

'kotlin > 문법' 카테고리의 다른 글

[kotlin] collection (List, Set, Map)  (0) 2021.01.14
[kotlin] arrays 배열  (0) 2021.01.14
[kotlin] Functions 함수  (0) 2021.01.13
[kotlin] 조건문 (if, when), 엘비스(elvis)  (0) 2020.12.28
[kotlin] 입출력과 사칙연산  (0) 2020.12.23

댓글