1. Introduction
Yeo-reobun-i sayongja-egae na-i-reul ipryeokhae jullae-yo-rago mudneun program-eul sseugo itda-go sangsanghaeboseyo. Sayongja-ga "abc"reul ipryeokhamnida. Yeoreobun-eun "jalmosdoen ipryeok"irago malhamnida. Geurigo… da-eum-eun mwo-yo? ifman itdamyeon program-eun geunyang kkeutkkaji ganda eumyeon jongryo-doeeo, sayongja-neun “geureom geurae” gateun neukkim-eul bada beorimnida. Loop-neun baro i ttaemun-e piryohae-yo: program-i haengdong-eul banbokhayeo, wonhaneun gyeolgwa-e dachageona — tto-neun jogeon-i cham-in dongan — gyeseok haedorok haneun geosibnida.
Hyeonsil-eseo loop-neun eodideun isseumnida: jaipryeok, “1buteo Nkkaji” gyesan, hap nugae, mokpyoreul hyanghae cheoncheonhi gakkawojigi. Geurigo matseumnida, loop-neun jalmos sseumyeon uidochi anhge “muhan”eul mandeulgi swiun ju do-guibnida (programmer-deul-eun gakkeum yeongwonham-do johahaejiman, compiler-neun hangsang geureochin anhseumnida).
2. while: syntax wa mental model
while loop-neun aju saramcheoreom ilhyeojimnida: “jogeon-i cham-in dongan — haera”. Kotlin-eseoneun daeumcheoreom boimnida:
while (condition) {
// loop body
}
Haeksim teukjing: body-e deureogagi jeon-e jogeon-eul geomsahamnida. Ttara-seo jogeon-i cheoeum-buteo falsemyeon body-neun han beon-do silhaengdoeji anhseumnida — geureonde i-ge “error”ga anira yuyonghan dongjag-imnida. Geuraeseo whileeun “uimi-ga inneun donganman silhaeng”haneun sanghwang-e wanbyeokhi matchseumnida.
whileeun club ipgu-ui gadeu gateun geos: “ticket isseoyo?” (jogeon). Ticket-eul eopmyeon, han beon-ui iteration-do an doeeo ipjang bulga-ibnida.
Program-ui heureum-eul nuneuro bogi wihan jageun flowchart:
flowchart TD
A[Start] --> B{condition?}
B -- no --> E[Exit loop]
B -- yes --> C[Loop body]
C --> D[End of iteration]
D --> B
Geurigo matseumnida: Kotlin-eun Kotlin-ijiman, yeogi-seo whileeun jeongmal jeontongjeog-in “eodiseodeun boneun geot”gwa gateun classic han hyeongtaero, nollaul geos eopseumnida. Gong-sik 예제-ui imperative style ( varwa loop-reul sseuneun gyeongu)eseo-do whileeun geunyang i 모양 geudaero-ibnida.
3. while patterns
Counter: 3ga-ji pil-su bu-bun
Cho-boja-ga loop-reul bomyeon cheot saeng-gak-eun daeche-ro ireon geot-ibnida: “O, banbok! Geureom mwo-ndeun banbokhamyeon… jache-ro meomchuneun geo aniya?” An meomchumnida. Loop-eun 도-um-i piryohae-yo.
Classic counter loop-eneun 3ga-ji bu-bun-i isseul ttaega manko, deungeul daeche-ro code-eseo geunyang boimnida:
- chogi 값 (loop jeon),
- continue condition (while (...) an-e),
- eonje-ga jogeon-i geojit-i doedorok byeonsu-reul byeongyeonghaneun code (body an-e).
Gajang swiun 예: 1buteo 5kkaji su-reul 출력:
fun main() {
var i = 1
while (i <= 5) {
println("i = $i") // i = 1, geu da-eum 2, 3, 4, 5
i = i + 1
}
}
Jujok: i byeonsu-neun gachi-reul bakkwo-ya 하므로 var로 seoneon-doeeosseumnida. I-ge valiyeosseumyeon compiler-ga jeongdanghage “bakkugi an hagiro haess잖아”라고 malhaess-eul geoyeyo.
Ije body-ga han beon-do silhaengdoeji anheul su inneun boundary 예를 bogo, i-ge yeoreobun-ui ihaereul geomjeung하는 “honesty check”daengnyeo:
fun main() {
var i = 10
while (i <= 5) {
println("Igeun chulryeokdoeji anseumnida")
i = i + 1
}
println("Loop-neun han beon-do silhaengdoeji anassseumnida") // Loop-neun han beon-do silhaengdoeji anassseumnida
}
i <= 5 jogeon-eun cheoeum-buteo falseiyagi ttaemun-e loop an-e deureogaji anassseumnida. Ireohge doeneun geosi ttaeroneun jeongmal piryohaejimnida: yegleul deulmyeon, “error-ga isseumyeon banbok”haneun logic-eseo error-ga cheoeum-buteo eopseul su isseunikka-yo.
Accumulation: sum gwa maximum
while loop-neun “step”eul 출력haneun geotppunman 아니라, gyeolgwa-reul nugaehaneun 데에도 yuyong합니다. Typical scenario: “yeoreo ga-ui su-ga isseuni hap-eul 구해라.” Ajik array/ list-reul an baewoss-eul ttae-neun 고정된 gaesugeul 다루거나 “N번 입력” 같은 형태로 연습하곤 합니다.
Gajang jageun geot-buteo: 1buteo 3kkaji-ui hap.
fun main() {
var sum = 0
var i = 1
while (i <= 3) {
sum = sum + i
i = i + 1
}
println("sum = $sum") // sum = 6
}
Yeogi-seo byeonsu yeokhal-i aju myeonghwak합니다: ineun “step”, sumeun “accumulator”입니다. Yeokhal-eul seok-eoseo (yeg: han byeonsureul counter-wa sum-euro hamkke sseumyeon) code-ga ‘jaksungja-man jaemiinneun joke’cheoreom doemnida.
Tto han-gae yuyonghan pattern-eun myeot ga-ui 입력 값 jung maximum-eul chajneun 것입니다. Na중eun deo pyeonhange haji man, 지금은 “bigyo하고 gyeongsin” logic-ga jungyo합니다.
Yegleul 들어 3ga-ui su-reul 처리한다고 가정해 봅시다 (tema-reul hechi지 않으려고 입력은 올바르다고 치겠습니다):
fun main() {
var max: Int? = null
var count = 0
while (count < 3) {
print("Suleul ipryeokhaese-yo: ")
val n = readln().trim().toInt()
if (max == null || n > max) max = n
count = count + 1
}
println("max = $max") // yeg: max = 42
}
Yeogi-seo maxneun nullable (Int?)로 mandeul-eossneunde, iyu-neun cheot ipryeok jeon-eun “maximum”i란 gaenyeom-i ajik eopseugi ttaemun입니다. I-ge nullable type-i 단지 “null-i eoryeoun tema” ttaemunman isseun geosi 아니라, ttaeroneun geunyang 솔직하게 “값은 나중에 생긴다”고 말하는 방법이라는 좋은 예입니다.
Infinite loop: wae saenggigo, eotteoke chajeon까
Ije beginner programmer-ui gajang keun “nori”: “program-eul silhaenghaessdeoni 멈췄어요.”reul malhae bopsida. Sil-eun daeche-ro meomchun geosi 아니라 — geunyang insaeng-ui uimi-reul chajaseo, gyesok gat-eun geos-eul muhanhi banbokhaneun geos-imnida.
Infinite loop-ui iyu-neun daeche-ro hana입니다: condition-i falsega doejil anhnunda. Byeonsu byeongyeong-eul kkamppakhaetgeona, dareun byeonsureul bakkuneun-de, 아니면 “bakkwo-ya 할 방향”eul jalmos bakkun geojyo.
Gajang classic han 실수:
fun main() {
var i = 1
while (i <= 5) {
println("i = $i")
// i = i + 1-eul kkamppakhaessseumnida
}
}
Yeogi-seo ineun hangsang 1, condition-eun hangsang cham, geuraeseo program-eun "i = 1"eul yeoreobun (tto-neun OS)가 “igeumani”라고 말hal ttaekkaji muhan히 출력할 것입니다.
Deo 교묘한 버전은, byeonsu-neun 업데이트하지만, condition-i jeoldae geojit-i doejil anhge mandeuneun 경우입니다:
fun main() {
var i = 1
while (i <= 5) {
println("i = $i")
i = i - 1
}
}
ineun 0, -1, -2…cheoreom gyesok jageojigo, condition i <= 5neun hangsang cham-uro 남습니다.
“anti-infinite” 규칙은 jom sikkeunhage deullijiman, jeongmal jal tonghamnida: whilereul sseun dwie nuneuro body an-e서 condition-e yeonghyang-eul juneun 줄을 chaj-euseyo. Chajji 못햇다면 — muhan loop-il hwaglyul-i aju nopsseumnida.
4. Jaipryeok gwa validation
Counter-do johjiman, whileeul salanghage 되는 gajang hyeonsiljeog iyu-jung hana-neun “robust input”입니다. Sayongja-neun 공백만 넣거나, 빈 줄, “saseung-do”cheoreom munjaro, 심지어 "42.0" (yeoreobun-eun Intreul wonhaetjiman)do ipryeokhal su isseumnida. Geureonde toInt()reul sseumyeon program-i crash nal su isseumnida. Ttara-seo “올바른 값이 나올 때까지 입력 반복” 시나리오-eneun trim() + toIntOrNull() johap-eul 씁니다.
readln()eun 한 줄 문자열을 통째로 읽고, toIntOrNull()eun 문자열이 숫자면 숫자를, 아니면 null을 돌려줍니다. I-ge whilee gwa 딱 맞습니다.
예: 나이(0~130 사이 정수)를 요청하고, 정상 결과가 나올 때까지 반복합니다.
fun main() {
var age: Int? = null
while (age == null) {
print("Nai-reul ipryeokhaese-yo (0..130): ")
val raw = readln().trim()
val parsed = raw.toIntOrNull()
if (parsed != null && parsed in 0..130) {
age = parsed
} else {
println("Jalmosdoen ipryeok-ibnida. Dasi si-dohaese-yo.")
}
}
println("Nai ga accepteu doeeosseumnida: $age") // yeg: Nai ga accepteu doeeosseumnida: 25
}
Wae pyeonhan-ga:
- Bad input-eseo crash nagi anseumnida — toInt()reul jikjeop sseuji 않기 ttaemun입니다.
- Loop condition-i aju ilgi swip습니다: “age-ga ajik eopseul ttaekkaji.”
- Body an-eseo “eotteon gyeongu-e input-i valid-haejineunji”ga myeonghwak합니다: parse-ga doego, range an-e deureoya 합니다.
Jungyo한 jageun point: parsed in 0..130 geomsa-neun parsedga nulli anil ttae-man 가능합 니다. Ttara-seo parsed != null && ...cheoreom sseumnida. I-geun yeoreobun-i imi &&wa || jogeon-sik-eseo 해본 same logic-ibnida.
5. Mini app: BudgetBuddy v0
Ije “jin짜 program”cheoreom boineun jageun scenario-reul han beon-e mandeureo bopsida. BudgetBuddy v0: 3ga-ui 지출을 입력받아 합계를 구하는 mini assistant라고 하죠. 핵심은 while loop와, break/continue 없이 (ajik an baewosseunikka) 잘못된 입력에도 튼튼하게 동작하도록 하는 것입니다.
Aidea: jeonghwakhi 3ga-ui 올바른 숫자ga piryo합니다. Sayongja-ga 이상한 값을 넣으면 — counter를 올리지 않고 다시 요청합니다. I-ge jeongmal jug-yo한 tech: counter-neun “success”일 때만 증가합니다.
fun main() {
var sum = 0
var entered = 0
while (entered < 3) {
print("Jichul №${entered + 1}reul ipryeokhaese-yo (jeongsu >= 0): ")
val raw = readln().trim()
val value = raw.toIntOrNull()
if (value != null && value >= 0) {
sum = sum + value
entered = entered + 1
} else {
println("Jalmosdoen ipryeok-ibnida. Jeongsu >= 0i piryohaemnida.")
}
}
println("3ga-ui jichul hap = $sum") // yeg: 3ga-ui jichul hap = 1200
}
Yeogi-seo yeokhal bunbae-ga eotteonji bwaseyo:
enteredneun “올바른 지출을 몇 개 받았는지”만 책임집니다. 입력이 나쁘면 enteredneun bakkwiji 않아서, 같은 “jichul 번호”e seo geudaero dashi mud습니다. I-ge hyeonsiljeog “jaipryeok”imnida — code dupe 없이요.
Tto gasi-seong: "№${entered + 1}"eun string template입니다. 안내가 친절해져서 sayongja-ga “jichul №2”reul 넣고 있다는 것을 알 수 있습니다.
6. Typical mistakes when working with while
Mistake №1: condition-e yeonghyang-eul juni byeonsu-reul byeongyeonghaji anassda.
Infinite loop-ui gajang heunhan wonin-eun condition-e deureo-gan byeonsu(i, entered, age)ga byeongyeongdoeji aneun 것입니다. Yuyonghan 습관: while (...)reul 쓰자마자, body an-eseo “eonje-ga condition-eul geojit-euro mandeuneun 줄”eul nuneuro chajseyo. Eopseumyeon — muhan loop-il ga-neungseong-i 큽니다.
Mistake №2: byeongyeong-eun 했지만 “방향”이 잘못돼 condition-i jeoldae geojit-i 안 된다.
Update-ga isseojiman logic-ga teull린 경우가 있습니다. Yeg: while (i <= 5)eseo i = i - 1cheoreom sseumyeon, “바뀌긴 하는데” 의미상 경계에서 멀어져 condition-eun 영원히 참으로 남습니다. 값이 경계에서 “도망”치는 게 보이면, 멈추고 증감 부호를 확인하세요.
Mistake №3: byeonsu yeokhal-eul seokk-eo loop-ga ihaehagi eoryeowojinda.
Han byeonsuro step-do 세고, sum-do 저장하고, “마지막 입력”까지 넣으려 하면, code-ga ilgi 어려워지고 고장 내기 쉬워집니다. 초보자에게 좋은 규칙: “han byeonsu = han yeokhal.” Counter 따로, accumulator 따로, parsed 값 따로.
Mistake №4: input loop-eseo toInt()reul sseoseo program crash-reul 만난다.
toInt()eun 입력 포맷을 확신할 때 좋습니다. Hajiman “sayongja input” 과제에서는 대개 확신이 없습니다. Geuraeseo jaipryeok-eneun toIntOrNull()gwa null check를 사용해야 합니다. Geureom program-i crash 나지 않고, 정중하게 다시 입력을 요청할 수 있습니다.
Mistake №5: nullil su inneun 값에 대해 비교/범위 체크를 시도한다.
Typical: val x = raw.toIntOrNull()reul 하고, daeum-e if (x >= 0)cheoreom sseuryeogo 합니다. Kotlin compiler-ga i-geol heo-yonghaji 않습니다 (dang-yeonhi). xga nullil su isseunikka-yo. Ol바른 순서는: meonjeo “nulli 아니지?”, geu da-eum “range-e match-hae?”입니다. Loop-eseoneun geomsa 순서 error-ga muhan banbok이나 올바른 입력을 영원히 못 받는 문제로 이어지기 쉬우니, 더 중요합니다.
GO TO FULL VERSION