14_반복문 while과 IntelliJ의 디버그모드

Jiyoon.lee·2023년 11월 18일
0

Java_inflearn

목록 보기
14/25

1. while

  • while은 반복문(iteration statements) 중에 하나이다.
  • 컴퓨터가 잘하는 일은 반복하면서 일을 처리하는 것이다.

2. while 사용법

  • while문은 탈출 조건식이 false를 반환할 때 while문을 종료하게 된다.
변수의 초기화
while (탈출 조건식) {
    탈출 조건식이 참일 경우 실행되는 코드;
    변수의 증감식;
}

3. 예제1

  • 1부터 5까지 출력하시오.
public class WhileExam1 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}
  • 실행 결과 :
1
2
3
4
5

4. while문과 break

  • while문에서 break를 만나면, 더이상 반복하지 않는다. break는 보통 조건문 if와 함께 사용된다.

5. 예제2

  • while(true){...}는 무한 루프(loop, 반복문)이라고 한다. 끝 없이 반복한다.
  • i가 11일 경우 while블록을 빠져나간다.
public class WhileExam2 {
    public static void main(String[] args) {
        int i = 1;
        while(true) {
            if (i == 11) break;
            System.out.println(i);
            i++;
        }
    }
}
  • 실행 결과 :
1
2
3
4
5
6
7
8
9
10

6. while문과 후위 증감식

  • 변수 뒤에 후위 증가식이 붙을 경우 변수가 사용된 이후에 값이 증가된다.
  • i와 10이 비교를 한 후 i가 증가한다.
public class WhileExam3 {
    public static void main(String[] args) {
        int i = 0;
        while(i++ < 10) {
            System.out.println(i);
        }
    }
}

*위 예제 코드는 좋은 예시는 아님

  • 실행 결과 :
1
2
3
4
5
6
7
8
9
10

7. while문과 continue

  • while문에서 continue를 만나면, continue이하 문장을 실행하지 않고 반복한다.

8. 예제3

  • 1부터 10 사이에 있는 짝수만 출력하시오.
public class WhileExam4 {
    public static void main(String[] args) {
        int i = 1;
        while(i++ < 10) {
            if (i % 2 != 0)
                continue;
            System.out.println(i);
        }
    }
}

*위 코드는 예제일뿐 while문 안에서 전위 연산자나 후위 연산자는 되도록 사용하지 않을 것

  • 실행 결과 :
2
4
6
8

0개의 댓글