JAVA 프로그래밍

[JAVA] 풀스택 개발자 부트캠프 004일차 ② 제어문 (do) while

selfdailycoding 2024. 12. 27. 11:01

while 순환문

 

1. 형식

while( 조건 ){
    처리
    연산식
	}

변수 선언
변수 초기화

 

2. 사용 예시

int w;
w = 0;
while(w < 10){
    System.out.println("w = " + w);
    w++;
}

 

3. 주의사항! 무한루프

빠져나오기 위해서 break문을 추가해야 함.

w = 0;
while(true) {      // 무한루프 오류 발생
    System.out.println("w = " + w);
    w++;
}
w = 0;
while(true){
    System.out.println("w = " + w);
    if(w == 100)
        break;
    w++;
}

 

4. 이중 while문

int w1, w2;
w1 = 0;
while( w1 < 5 ){
    System.out.println("w1 = " + w1);
    w2 = 0;
    while(w2 < 3){
        System.out.println("\tw2 = " + w2);
        w2++;
    }
    w1++;
}

 

5. do while문

조건상으로 맞지 않아도 do에 의해 변수가 실행은 되기에 사용 선호도가 낮음.

int w3;
w3 = 10;
do{
    System.out.println("w3 = "+ w3);
    w3++;
}while(w3 < 10);