CodeGym /행동 /Kotlin SELF /for: beomwi a..b wa munjayeol munja sunhoe

for: beomwi a..b wa munjayeol munja sunhoe

Kotlin SELF
레벨 4, 레슨 3
사용 가능

1. Ije imi while i itneunde, wae for ga pilyohalkka?

Soljikhage 말하ja면, while 로 geoui modeun geos-eul sseul su itsseumnida… haji만 gakkeum-eun geugeu “hyeongtae” ga mikroseukopeuro mogeul bakneun geotcheoreom boyeoseo: gisuljeog-euro-neun ganeunhaji man maengseureopgo eosaekhamnida. for neun banbok-i 미리 junbidoen “gap-ui woncheon” eul ttareul tta pilyohamnida: su beomwi, munjayeol, baeyeol, keollek-syeon. Kotlineseo for neun won래 geureoke seolgye doe-eotseumnida: “han beon-e hana ssik element-reul naeryeojuneun geos-eul sunhoeha라.”

Ilsang ui bigyoro: while — “naengjanggo-e eumsik-i isseumyeon gyesok meok-eora”, geurigo for — “s탕 5 gae meok-eora” tto는 “dan-eo ui modeun geulja-reul hanna ssik bomyeonseo cheoriha라”. du gyeong-u modu dongjakeul banbokhajiman, hujaneun kaunteo-reul jigeop jageuro gwanrihaji ango도 banbok-eul pyo-hyeonhagi swip습니다.

2. for munbeop: “gak … e daehae … aneseo”

for neun “gak element x reul gap woncheon-eseo gajyeowa momcheoreul silhaengha라” cheoreom ilban munjangcheoreom ilk힙니다. jeonche hyeongtae-neun da-eum gwa gatseumnida: for (item in source) { ... }. i geon majiagi-do, jumun-do anigo—danji maeu pyeonrihan pyo-gi-ipnida. yeogi-eun sasil sangse han jab-eul sumgimnida: daeum gap-eul gajyeo-ogo, momcheoreul silhaenghago, daeum-euro neomeoganeun geot.

Cheot jeom-eulo iksukhaejyeoya hal saenggak: saik geueseo seuneun byeonsu (item, i, ch) neun “hyeonjae gap”이지, “naega jigeop jageuro 1 ssik 올려야 하는 kaunteo” ga 아닙니다. for eseo georeum jinhaeng-eun loop ga jaseon-eul gajigo (dangsin daesin) cheorihago, geugeu ttaemun-e kodeu-ga deo jjalbo-go pyeonanhaejimnida.

Gajang dan순han 예: dan-eo 목록-eul sunhoehae boda (ajik keollek-syeon-eul gipi baeuji anado, idea-reul boyeojugi wihan 데모):

fun main() {
    val shoppingList = listOf("Milk", "Bananas", "Bread")

    for (item in shoppingList) {
        println(item)
    }
    // Milk
    // Bananas
    // Bread
}

3. for eseo ui beomwi a..b

Beomwi a..b neun “a eseo b kkaji ui modeun su-reul gajyeowa라” 라고 말하는 bangbeop-imnida. yeogiseo haeg심 dan-eoneun “gyeong-gye pohnam” 입니다. 1..5 reul sseumyeon 1, 2, 3, 4, 5 — chong daseot beon-ui step-i doemnida. i beomwi-neun bo통 N beon banbokhagi na “~eseo ~kkaji” ro jinhaenghal tta gajang manhi sseumnida.

Kotlin munseo-eseo for neun baeyeol-gwa keollek-syeon cheoreom beomwi(ranges) do sunhoehal su inneun loop ro seolmyeongdoemnida. geugeu mal-eun, for (i in 1..10) i Kotlineseo “wonrae geureoke sseuneun” seuta-il i라는 geos입니다—eojjeoda 한 번 sseuneun teukbyeolhan trick-i 아닙니다.

Mini 예: “5 georeum ha라”

Gajang tuseonghan 예 reul mandeureo bopsida—danji georeum beonho-reul chullyeokhae bopsida:

fun main() {
    for (i in 1..5) {
        println("Step $i")
    }
    // Step 1
    // Step 2
    // Step 3
    // Step 4
    // Step 5
}

Yeogiseo du 가지-reul gippeuge bwajusyeoya hamnida.

Cheot째, uri-neun sseuji anhseumnida: i = i + 1. i reul byeongyeonghaneun geon loop iga 하고, uri-neun hyeonjae i reul sayonghal 뿐입니다.

둘째, loop aneseo ui i neun val cheoreom dongjak합니다: 각 iteoreisyeon 마다 “hyeonjae gap” 으로 saeropge mandeureojimnida. 만약 i = i + 1 reul si도하면 컴파일러-ga bulpyeon해합니다. geureonde geugeu geollae deo johseumnida: logik-eul 망칠 su inneun bangbeop-i jul-eodeul ttaemun입니다.

“gyeong-gye pohnam” jeong리 teb-ul

Hokshi silsu-reul jul-igi wihayeo, han beon jasughae 두면 johseumnida:

Beomwi Naebu gap Iteoreisyeon su
1..1
1
1
1..3
1, 2, 3
3
2..5
2, 3, 4, 5
4

“1 buteo sijakhaeseo jeonghwakhi N beon banbok” i pilyohamyeon, daebu bun-ui gyeong-u 1..N i jal mat습니다.

for ro “N beon banbok” — kaunteo jigeop gwanri eopsi

Jeoneun while lectio-eseo jeontongjeogin “kaunteo” reul haebwatseumnida: var i = 1 seon-eon, jogeon geomsa, loop aneseo i 증가. i geon jeongsang이고 gakkeum pilyohamnida. haji만 georeum-i moksollihan seonhyeong (1, 2, 3…) il tta, for ga kodeu-reul deo compact hage, deo ilkh기 swip게 만듭니다: loop head-eseo gyeonggye-ga han nun에 들어옵니다.

Silmujeog-euro malhae, munje-ga “10 beon 시도해라”, “3 gae 값을 읽어라”, “1 buteo n kkaji ui hap-eul 구하라” cheoreom deull린다면, for ga bo통 cheot beonjjae hu보가 됩니다. kaunteo-reul ol리지 anaseo 무한 루프 위험이 줄어드는 데, i유-neun kaunteo-reul “kkeok” ol리지 않는 실수를 할 여지가 작아지기 때문입니다.

Sum: 1 buteo n kkaji ui hap

1 buteo n kkaji su-ui hap-eun yeonseub 예제입니다. jeongmal saenghwal-eseo su-reul haphae야 해서라기 boda (hoegye-ga isseumyeon dareun mal-eul 할 수도 있지만), han 번에 세 가지-reul yeonseub hagi ttaemun입니다: 누적 변수, beomwi, gyeong-gye cheori.

Mini peurogeuraem-eul mandeureo bopsida: n reul 입려ok받고, 올바르고 n >= 1 imyeon for 로 hap-eul 구합니다.

fun main() {
    print("Enter n (>= 1): ")
    val n = readln().trim().toIntOrNull()

    if (n != null && n >= 1) {
        var sum = 0
        for (x in 1..n) sum += x
        println("sum = $sum")
    } else {
        println("Invalid n")
    }
}

Yeogiseo jageun 가독성 팁이 있습니다: for (x in 1..n) sum += x 는 momcheori han 줄(명령 1개) il tta 한 줄로 써도 됩니다. Kotlin-un geureoke hago, gakkeum pyeonri합니다. haji만 loop aneseo 2–3 gae dongjak-eul 한다면, { } reul sseoseo “줄바꿈 없는 si” cheoreom boiji 않게 하는 게 좋습니다.

for (x in 1..n) ga “saenggak” haneun bangsik

Cheoeum baeu-neun saram-e겐, loop-eul “mekanijeum” 으로 sangsang하면 ihae-ga swip습니다. beomwi for ui dan순화된 logic-eun da-eum cheoreom boleo nun-i doemnida (Kotlin kodeu ga 아니라, “imi-eulo eotteoke dongjakha느냐”):

flowchart TD
    A[Loop start] --> B[Take next value x from the range]
    B --> C{Is there a value?}
    C -- no --> D[Exit the loop]
    C -- yes --> E[Execute the loop body]
    E --> B

i geon Kotlin munseo ui idea-wa jal matseumnida: for neun iterator-reul tonghae element-reul naeryeojuneun dae상-eul sunhoe하고, beomwi-neun optimization 된 sunhoe-ro compile doemnida.

4. downTo 와 step: banghyang gwa georeum

Silje munje-eseo-neun gakkeum kkeut-eseo sijakhaeya 하고(ye: majimak gap-eul cheoeum chullyeok), gakkeum-eun han georeum geonneotteo cheorihago 싶고(ye: jjaksu 위치만), tto gakkeum-eun du ga jji modu pilyoham니다. Kotlin-un i-reul wihayeo du 가지 maeu dan순han 구문을 제공합니다: yeok방향-eun downTo, georeum 크기(neop) 는 step.

Meonjeo gajang dan순han yeok 카운트:

fun main() {
    for (i in 5 downTo 1) {
        print("$i ")
    }
    // 5 4 3 2 1
}

downTo 를 사용하면 양 끝 값이 모두 beomwi에 포함됩니다.

Ije georeum-eul chuga해 “2 씩”:

fun main() {
    for (i in 10 downTo 0 step 2) {
        print("$i ")
    }
    // 10 8 6 4 2 0
}

Yeogiseo-neun oenjjok-eseo oreunjjok-euro 읽으면 swip습니다: “10 eseo sijak, 0 kkaji naeryeogago, georeum 2.”

5. for eseo munjayeol sunhoe

Ije lectio ui gajang “saramseureoun” bubun-euro gajabopsida: munjayeol-eun 텍스트이고, 텍스트는 munja-ro iru-eojyeo itsseumnida. maeu jaru han geon munjayeol-eul 한 글자씩 bo면서 mueonga-reul 세고 싶습니다: gongbaek 몇 개인지, 숫자 몇 개인지, 텍스트 안에 @ 가 있는지, geulja a ga myeot beon 나오는지 (ne, ije geoui mini detektib imnida).

Kotlin-eseo munjayeol-eun for 로 jikjeop sunhoe할 수 있습니다: for (ch in text) { ... }. 각 iteoreisyeon마다 ch 는 Char 타입, 즉 “han munja” ga 됩니다. Char e dae한 별도 lectio-eul ajik an baewoss더라도, yeogiseo-neun “han geulja/han suja/han 기호” 라고 ihae하면 충분합니다.

Geurigo jungyo: munjayeol-e dae한 for 도 gibon 원칙-eun gat습니다—“gap woncheon-eul sunhoe한다.” dan지 woncheon이 munjayeol로 바뀐 것뿐입니다. Kotlin munseo-eseo-do for 는 iterator-ga inneun eotteon 객체에도 작동한다고 gangjo합니다. munjayeol-i baro geureon 객체입니다.

Modeun munja-reul han gae ssik chullyeok하기

fun main() {
    val word = "Kotlin"

    for (ch in word) {
        println(ch)
    }
    // K
    // o
    // t
    // l
    // i
    // n
}

Ne, i geon “90nyeondae 프린터처럼 han 글자씩 찍어보며 감성을 느낀다” 처럼 보일 수 있습니다. haji만 silje gachi-neun i geot: ije 각 munja-reul dae상-euro geomsa나 카운트 작업을 할 수 있습니다.

Counting: gongbaek gwa 숫자

Ije jageun “Text Analyzer v0” (beojeon 0-0-0-jeongmal imi-eulo 아주 초반) reul mandeureo bopsida: peurogeuraem-i munjayeol-eul il고, geu 안에 gongbaek 몇 개, 숫자 몇 개가 있는지 셉니다. eotteon bokjaphan geot-do an 씁니다—for, if, geurigo du gae ui kaunteo-man.

“i munja-ga 숫자인지 아닌지” 판별하려면, munja를 '0' 과 '9' gyeonggye와 비교하면 됩니다. munja는 (코드 포인트 순서 때문에) 대소 비교가 가능하므로, 초보에겐 조금 낯설게 들릴 수 있지만, 숫자 구간이나 라틴 알파벳 구간에서는 매우 잘 동작합니다.

fun main() {
    print("Enter a string: ")
    val text = readln()

    var spaces = 0
    var digits = 0

    for (ch in text) {
        if (ch == ' ') spaces += 1
        if (ch >= '0' && ch <= '9') digits += 1
    }

    println("Spaces: $spaces, digits: $digits")
}

Sayongja-ga Kotlin 2.3 reul 입력하면, chullyeok-eun dae략 ireon 식입니다:

// Enter a string: Kotlin 2.3
// Spaces: 1, digits: 2

Yeogiseo uri-neun han 가지 yuhyohan 습관-euro jeomjinjeok-euro gajyeogamnida: for 는 종종 조건에 따라 업데이트하는 “kaunteo” (var) 와 함께 옵니다.

6. Eotteoke seontaekhal까: while, do-while, tto는 for

Ije “jal못된 loop seontaek” eul mag아주는 jungyo한 생각을 말하겠습니다. Gisuljeok-euro-neun manhi munje-reul 여러 loop로 풀 수 있습니다. haji만 좋은 스타일은, uimi-reul gajang jal deureonae-neun loop-eul 고르는 것입니다.

while 과 do-while 는 banbok 횟수가 미리 알 수 없을 때 유용합니다: “입력이 잘못된 동안 반복해라” 또는 “맞힐 때까지 시도해라.” 반면 for 는 미리 “step woncheon” 을 설명할 수 있을 때 적합합니다: su beomwi 또는 munja yeoll. Kotlin munseo-eseo도 이렇게 말합니다: for 는 keollek-syeon, baeyeol, beomwi, 그리고 iterator-reul 제공하는 모든 것을 sunhoe합니다.

빠른 판단을 위한 teb-ul:

Sanghwang Bo통 i geot-i deo 잘 읽힘
Jogeon-i cham-in 동안 banbok
while
Dongjak-i 최소 han 번은 silhaeng돼야 함
do-while
a buteo b kkaji su-reul sunhoe
for (i in a..b)
Munjayeol ui modeun munja sunhoe
for (ch in text)

7. for sayong si jeonhyeongjeogin silsu

Silsu №1: beomwi a..b ga “b reul pohnam haji anneunda” go saenggak하기.
I geon dareun eoneoeseo 넘어오거나, dan순 부주의로 생기는 gajang heunhan hon란입니다. i kurs-eseo-neun 명확히 고정합니다: .. 는 양쪽 gyeonggye-reul 모두 포함합니다. 1, 2, 3, 4, 5 reul 찍고 싶으면 1..5 reul 쓰면 되고, 정확히 그렇게 나옵니다.

Silsu №2: for aneseo loop byeonsu-reul jigeop byeongyeongharyeogo 시도하기.
for eseo loop byeonsu-neun “hyeonjae gap” 이지, 마음대로 가지고 노는 장난감이 아닙니다. i = i + 1 cheoreom sseuryeogo 하면 컴파일러가 막습니다. geugeu geollae 좋은 일입니다: georeum-i kkaeg거나 loop-ga 예측 불가능해지는 것을 방지합니다. 만약 georeum-eul 직접 제어해야 한다면, 그건 이미 while 후보입니다 (oneul-eun 원칙만 기억해 둡시다).

Silsu №3: “ol바르게 입력될 때까지” reul for 로 처리하려고 하기.
Gakkeum-eun “10 beon 물어보면 eojjeom 한 번은 맞겠지” 라고 쓰고 싶을 수 있습니다. haji만 사용자가 계속 잘못 입력하면, 시도 횟수만 끝나서 잘못된 상태가 되거나, logic-eul 괜히 복잡하게 만들게 됩니다. “올바를 때까지 반복” 은 while 이나 do-while 이 더 자연스럽습니다.

Silsu №4: han kaunteo byeonsu-e 여러 의미를 섞기.
Ye: hap, 숫자 개수, gongbaek 개수-reul 동시에 세다 보면, “달라야 하는 kaunteo” 를 실수로 업데이트하기 쉽습니다. i geon for ui 문제가 아니라, 가독성 문제입니다. haeg심 규칙은 단순합니다: han byeonsu — han 의미. digits 는 숫자, spaces 는 gongbaek, sum 은 합, 그리고 x reul 만능 병사로 만들지 마세요.

Silsu №5: 빈 문자열과 “amu 것도 일어나지 않음” eul 잊기.
사용자가 빈 문자열을 입력하면, for (ch in text) 는 한 번도 실행되지 않습니다—geureonde geu geon 정상 동작입니다 (while 도 처음부터 jogeon-i false 면 바디가 0번 실행되는 것과 동일). panik 하지 마세요: peurogeuraem-i 고장 난 것이 아니라, 처리할 문자가 없다는 것을 정직하게 반영한 것입니다.

1
과제
Kotlin SELF, 레벨 4, 레슨 3
잠금
타워의 층
타워의 층
1
과제
Kotlin SELF, 레벨 4, 레슨 3
잠금
경로 합계
경로 합계
1
과제
Kotlin SELF, 레벨 4, 레슨 3
잠금
문자 번호 매기기
문자 번호 매기기
1
과제
Kotlin SELF, 레벨 4, 레슨 3
잠금
문자열 검사
문자열 검사
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION