# for & forEach

주어진 조건이 충족되는 동안 특정 작업을 반복

```java
package sec04.chap03;

public class Ex01 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i); // 🔴
        }
    }
}

```

* 실행 과정
  1. 루프 안에서 사용할 변수 초기화
  2. 루프를 실행하기 위한 조건 확인
  3. 조건을 충족시 실행할 내용
  4. 각 루프가 끝날때마다 이행할 내용
* 1번 이후 2를 충족할 동안 2\~4 반복
* 변수명은 원하는대로 사용 가능
  * 일반적으로 기본형에는 `i` 를 많이 사용 - *문맥에 따라 index를 뜻함*

```java
package sec04.chap03;

public class Ex02 {
    public static void main(String[] args) {
        //  루프 블록 안에서 변수값을 바꾸는 것으로 4번 과정 대신 가능
        for (int i = 0; i < 10;) {
            System.out.println(i);
            i += 2;
        }


        System.out.println("\n- - - - -\n");

        for (double d = 123.45; d > 0; d -= 32.1) {
            System.out.println(d);
        }

        for (String s = ""; s.length() < 11; s += s.length()) {
            System.out.println(s);
        }

        System.out.println("\n- - - - -\n");

        //  💡 쉼표로 구분하여 여럿 사용 가능
        //  ⚠️ 변수의 자료형은 한 종류만 가능 (혼용 안 됨)
        for (byte a = 0, b = 10; a <= b;) {
            System.out.printf("a: %d, b: %d%n", a++, b--);
        }
    }
}

```

무한 루프

무한루프는 프로그램을 정지시킴

```java
package sec04.chap03;

public class Ex03 {
    public static void main(String[] args) {
        //  종료조건이 없는 for 루프
        for (;;) {
            System.out.println("영원히");
        }
        System.out.println("닿지 않아"); // ⚠️ 실행되지 않음


        //  종료조건을 만족시키지 못하는 무한루프
        for (int i = 0; i < 10; i++) {
            System.out.println("그래도");
            i--;
        }
        System.out.println("닿지 않아"); // ⚠️ 실행되지 않음
    }
}

```

### 배열의 루프

```java
package sec04.chap03;

public class Ex04 {
    public static void main(String[] args) {
        //  4의 배수 차례로 10개 배열에 담기
        int count = 10;
        int[] multiOf4 = new int[count];

        for (int i = 1, c = 0; c < count; i++) {
            if (i % 4 == 0) {
                multiOf4[c++] = i;
            }
        }
        //  💡 배열 순환 (기본적인 방법)
        for (int i = 0; i < multiOf4.length; i++) {
            System.out.println(multiOf4[i]);
        }
    }
}

```

### 중첩 루프

```java
package sec04.chap03;

public class Ex05 {
    public static void main(String[] args) {
        //  구구단 예제
        for (int i = 1; i < 10; i++) {
            for (int j = 1; j < 10; j++) {
                System.out.printf("%d X %d = %2d%n", i, j, i * j);
            }
        }

        String[][] quotesInLangs = {
                {
                        "I am vengeance.",
                        "I am night.",
                        "I am Batman.",
                },
                {
                        "나는 복수를 하지.",
                        "나는 밤이지.",
                        "나는 배트맨이지.",
                },
        };

        String result = "";
        for (String[] quotes : quotesInLangs) {
            for (String quote : quotes) {
                result += quote + " "; // 🔴
            }
            result = result.trim().concat("\n");
        }

        System.out.println(result);
    }
}

```

### continue와 break

```java
package sec04.chap03;

public class Ex06 {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {

            //  💡 continue : 한 루프만 건너뜀
            if (i % 3 == 0) continue;

            //  💡 break : 블록 전체를 종료
            if (i == 10) break;

            System.out.println(i);
        }

        System.out.println("\n- - - - -\n");

        String str = "호";

        //  ⭐️ 무한루프 탈출에 사용 가능
        for (;;) { // 다음 강의 while을 더 많이 사용
            str += "롤";
            System.out.println(str);
            if (str.length() == 30) break;
        }

        str += "로";
        System.out.println(str);
    }
}

```

```java
    System.out.println("\n- - - - -\n");

    //  💡 label : 중첩 루프에서 어느쪽을 continue, break 할 지 구분
    outer:
    for (int i = 0; i < 10; i++) {

        inner:
        for (int j = 0; j < 10; j++) {
            if (j % 2 == 0) continue inner;
            if (i * j >= 30) continue outer;

            if (j > 8) break inner;
            if (i - j > 7) break outer;

            System.out.printf("i: %d, j: %d%n", i, j);
        }
    }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/java/section3./for-and-foreach.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
