코틀린+안드로이드

10. for, while

으누아빠 2020. 7. 17. 14:41
반응형

for, while

  • 출처 https://www.youtube.com/watch?v=IDVnZPjRCYg&t=8s [Code with Joyce]
  • for (i in items) {} items수 만큼 반복
  • for ((index, value) in items.indices) {} 배열이나 리스트의 index값을 이용하여 반복
  • for (i in items.withIndex) {} 배열이나 리스트의 index값을 이용하여 반복
  • for (i in 1..10) {} 1 부터 1씩 증가하며 10까지 반복
  • for (i in 1 until 10) {} 1부터 1씩 증가하며 10을 제외하고 반복
  • for (i in 1..10 step 2) {} 1부터 2씩 증가하며 10까지 반복
  • for (i in 10 downTo 1) {} 10부터 1씩 감소하며 1까지 반복
  • for (i in 10 downTo 1 step 2) {} 10부터 2씩 감소하며 1까지 반복
fun main(){
    mfor()
}

fun mfor(){
    val students : ArrayList<String> = arrayListOf("a", "b", "c", "d")
    for (name : String in students) {
        println("${name}")
    }
    //결과값
    // a
    // b
    // c
    // d

    val items = listOf("apple", "banana", "kiwifruit")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
    //결과값
    // item at 0 is apple
    // item at 1 is banana
    // item at 2 is kiwifruit

    //1부터 10까지 반복하여 합산
    var sum : Int = 0
    for (i: Int in 1..10) {
        sum += i
    }
    println(sum) //결과값 55

    var sum : Int = 0

    // 1 부터 2씩 증가하며 10까지 반복
    for (i: Int in 1..10 step 2) {
        sum += i
    }
    println(sum) //결과값 25


    // 10부터 1씩 감소하며 1까지 반복
    var sum : Int = 0

    for (i: Int in 10 downTo 1) {
        println(i)
    }

    // 결과값
    //    10
    //    9
    //    8
    //    7
    //    6
    //    5
    //    4
    //    3
    //    2
    //    1

    //1부터 1씩 증가하며 1을 제외하고 반복
    for (i: Int in 1 until 10) {
        println(i)
    }

    //결과값
    // 1
    // 2
    // 3
    // 4
    // 5
    // 6
    // 7
    // 8
    // 9

    // index, 데이터 값을  같이 출력
    for ((index : Int, name : String) in students.withIndex()) {
        println("${index}번째 학생:${name}")
    }
    //결과값
    // 0번째 학생:a
    // 1번째 학생:b
    // 2번째 학생:c
    // 3번째 학생:d
}
  • while
fun main(){
    mWhere()
}

fun mWhere(){  
    var index : Int = 0  
    while(index < 10) {  
        println("current index : ${index}")  
        index++  
    }
}  

// 결과값
//    current index : 0
//    current index : 1
//    current index : 2
//    current index : 3
//    current index : 4
//    current index : 5
//    current index : 6
//    current index : 7
//    current index : 8
//    current index : 9

'코틀린+안드로이드' 카테고리의 다른 글

12. Lambdas 람다  (0) 2020.07.17
11. class  (0) 2020.07.17
9. Nullable / NonNull  (0) 2020.07.17
8. List, ArrayList  (0) 2020.07.16
7. Array  (0) 2020.07.16