2024-06-21
This commit is contained in:
72
Writerside/topics/Loop.md
Normal file
72
Writerside/topics/Loop.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# 반복
|
||||
|
||||
## for .. in ..
|
||||
|
||||
```kotlin
|
||||
for (item: Int in array){
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
레인지와 함꼐 사용할 수도 있습니다.
|
||||
|
||||
```kotlin
|
||||
for (i in 1..10){
|
||||
// ...
|
||||
}
|
||||
|
||||
for (i in 6 downTo 0 step 2){
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
인덱스가 필요한 경우에는 `indices` 또는 `withIndex()`를 사용해서 다음과 같이 할 수 있습니다.
|
||||
|
||||
```kotlin
|
||||
for (i in array.indices) {
|
||||
println(array[i])
|
||||
}
|
||||
```
|
||||
|
||||
```kotlin
|
||||
for ((index,value) in array.withIndex()) {
|
||||
println("element[$index] is $value.")
|
||||
}
|
||||
```
|
||||
|
||||
## while
|
||||
|
||||
```kotlin
|
||||
while (x > 0) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### do .. while
|
||||
|
||||
```kotlin
|
||||
do {
|
||||
// ...
|
||||
} while (x > 0)
|
||||
```
|
||||
|
||||
# 분기
|
||||
|
||||
- return
|
||||
|
||||
- break
|
||||
|
||||
- continue
|
||||
|
||||
|
||||
## 라벨
|
||||
|
||||
표현식의 앞에 '@'을 사용해서 라벨을 붙여 둔 다음, `break`나 `continue` 뒤에 '@'을 사용해서 점프할 라벨 위치를 지정할 수 있습니다.
|
||||
|
||||
```kotlin
|
||||
loop@ for (i in 1..10) {
|
||||
for (j in 1..10) {
|
||||
if (...) break@loop
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user