while 루프

중급 Java

Jim White

Java Developer

while 루프 동작 방식

  • 먼저 조건 확인
    • 참이면 본문 코드를 실행
    • 거짓이면 루프 종료
  • 반복: 조건 확인 후 수행 결정

while 루프 구성도

중급 Java

while 루프 구문

while (condition) {

  // Run this code

}
  • 구문은 if와 유사
  • if와 달리 여러 번 실행 가능
중급 Java

while 루프 예시

// 5보다 작은 수 출력
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 1;
}
1
2
3
4
중급 Java

무한 while 루프

  • 변수 업데이트 누락
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 0;
}

 

➡ 프로그램이 멈춤

  • 조건이 항상 true
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter - 1;
}
중급 Java

증감 할당 연산자

int counter = 0;

// Same as counter = counter + 3
counter += 3;

유사 연산자: -=, *=, /=, ...

중급 Java

break

  • breakwhile을 일찍 종료할 수 있으나 권장되진 않음
int counter = 1;
while (counter < 5){
    System.out.println("Counter: " + counter);
    if (counter == 3) {
        break; // Exit the loop when counter is 3
    }
    counter+=2;
}
Counter: 1
Counter: 3
중급 Java

요약

// while 루프: 20보다 작은 짝수 출력
int counter = 2;

while (counter < 20){
  System.out.println(counter);
  counter *= 2;

  // counter가 홀수면 종료
  if (counter % 2 == 1){ // counter % 2 is counter modulo 2
    System.out.println("Something went wrong, counter is odd.");
    break;
  }
}
중급 Java

연습해 봅시다!

중급 Java

Preparing Video For Download...