반복문(for, while, do~while)(+break, continue, 확장 for문)

YongJun·2023년 8월 26일

JAVA

목록 보기
5/24
post-thumbnail

for vs while vs do~while

  • for
    반복 횟수가 정해진 경우
		int i;
		for(i=1; i<=10; i++) {
			System.out.print(i); //12345678910
		}
		System.out.println("탈출 i = "+ i); //탈출 i = 11
  • while
    무한 루프나 특정 조건에 만족할 때까지 반복해야하는 경우
		int a = 0;
		while(a<10) {
			a++;
			System.out.print(a+" ");
		}
		System.out.println(); //1 2 3 4 5 6 7 8 9 10 
  • do~while
    조건에 따라 반복을 계속할지를 결정할 때 사용하는 것은 while 문과 동일합니다.
    다만, 무조건 중괄호 {} 블럭을 한번 실행하고, 조건을 검사하여 반복을 결정합니다.
		int a = 0;
		do {
			a++;
			System.out.print(a+" ");
		}while(a<10);
		System.out.println(); //1 2 3 4 5 6 7 8 9 10 

break vs continue

  • break

    만나는 즉시 반복문 전체 탈출(switch문에서도 사용됨)

    public class Main {
    
       public static void main(String[] args) {
           for(int i=1; i<5; i++){
               if(i==3) break;
               System.out.println(i);
           }
    
           System.out.println("반복문 끝!");
       }
    }
    //1
    //2
    //반복문 끝!
    
  • continue

    만나면 해당 반복부분 탈출 후 다음반복실행

    public class Main {
    
       public static void main(String[] args) {
           for(int i=1; i<5; i++){
               if(i==3) continue;
               System.out.println(i);
           }
    
           System.out.println("반복문 끝!");
       }
    }
    //1
    //2
    //4
    //반복문 끝!```

확장 for문

  • 배열 내의 모든 값을 반복하는 for문의 향상된 형태.
    인덱스 값이 필요하지 않을 때 간결하고 유용하다.

  • 형식

    for (요소타입 변수명: 반복대상) {
        실행영역;
    }
  • EX)

    String[] arrFruit = {"banana", "tomato", "apple"};
    
    for(String fruit:arrFruit) {
        System.out.print(fruit+" "); //banana tomato apple
    }
profile
개(발자어)린이

0개의 댓글