[Day 2 | Java] Condition & Loop

y♡ding·2024년 10월 15일
1

데브코스 TIL

목록 보기
3/163

모든 프로그램은 위에서 아래로 실행된다. 하지만 프로그램 제어를 통해 흐름을 변화시킬 수 있다.

  • 조건에 의한 분기
  • 조건에 의한 반복
  • 기타 제어

1️⃣ 조건에 의한 분기

사용자의 선택에 따라 진행하는 일의 형태를 분기시킬 수 있다.

  • if

  • ìf ~ else

  • 중첩 if

  • ìf ~ else if ~ else if ~ else

  • switch ~ case ~ default

    	// 98 / 10 = 9, 96 / 10 = 9, 94 / 10 = 9를 이용
    public class ConditionEx11 {
       public static void main(String[] args) {
          /*
               점수(score)
               점수가 90점 이상 - A출력
               점수가 80점 이상 - B출력
               점수가 70점 이상 - C출력
               점수가 60점 이상 - D출력
               기타           - F출력
            */
           System.out.println("시작");
    
            int score = 90;
    
            switch (score / 10) {
               case 9 :
                   System.out.println("A");
                   break;
               case 8 :
                   System.out.println("B");
                   break;
               case 7 :
                   System.out.println("C");
                   break;
               case 6 :
                   System.out.println("D");
                   break;
           default :
           System.out.println("F");
           }
           System.out.println("끝");
       }
    }

    ** 조건에 의한 분기는 선택과 필터링, 두 가지 의미가 있다.

2️⃣ 조건에 의한 반복

  • for문 : 초기값. 조건, 증감 고려**

    // ascii code 이용
    public class LoopEx03 {
       public static void main(String[] args) {
           // A ~ Z 출력
           // ascii
           // A - 65
    
           System.out.println("시작");
    
           for (int i = 65; i < 91; i++) {
               System.out.println((char)(i));
           }
    
           System.out.println();
    
           for (char ch = 'A'; ch <= 'Z'; ch++) {
               System.out.println(ch);
           }
    
           System.out.println("끝");
       }
    }
// for문의 응용 
public class LoopEx08 {
    public static void main(String[] args) {
        
        // 처음과 끝 : 유한루프
        for (int i = 1; i <= 5; i++) {
        }

        // 무한루프 -> 시스템 정지
        // 프로그램 필요에 따라 무한루프 사용 가능
        // 조건 성립이 잘못
        for (;;) {
        }

        // int i = 1;
        for (; i<= 5; i++) {
             System.out.println("Hello");
        }

        // 초기식 / 조건식 / 증감식 -> 2개 이상 가능
        for (int i = 10, j = 5; i <= 5 || j <=10; i++, j++) {
            System.out.println(i + " / " + j) ;
        }
    }
}
public class LoopEx09 {
    public static void main(String[] args) {
        // 중첩반복문
        // 반복문 1 : 1차원
        // 반복문 2 : 2차원
        // 반복문 3 : 3차원

        System.out.println("시작");

        // 반복횟수 
        // 외부(5) / 내부(5) => 25번
        for (int i = 1; i <= 5; i++) {
            // 5번
            System.out.println("?");

            for (int j = 1; j <= 5; j++) {
                System.out.println(i + " / " + j);
            }
        } 

        System.out.println("끝");
    }
}
  • while

  • do ~ while

    ** 반복횟수

📌 반복문의 생략과 탈출: continue & break

continue문과 break문은 while문과 같은 반복문과 관련이 있다.
그런데 이 두 문장은 보통 if문과 함께 쓰이므로 알아두자.

break문
break는 반복문을 빠져 나올 때 사용하는 키워드이다.
break문을 실행하면 break문을 가장 가까이서 감싸고 있는 반복문 하나를 빠져 나오게 된다.
break문이 if문과 함께 쓰였다고 해서 if문을 빠져 나오는 것으로 이해하면 안된다!

continue문
break문과 마찬가지로 반복문 안에 삽입된다.
반복문 안에서 continue문을 만나면 실행중인 위치에 상관없이 반복문의 조건검사 위치로 이동한다. 그리고 검사결과 반복조건이 여전히 '참'이라면 반복영역을 다시 실행하게 된다.
continue문 이후로 생략을 하고, 다시 실행하게 된다.

break
반복문 실행 중 특정 조건을 만족하면 반복문을 벗어남
continue
반복문 실행 중 특정 조건을 만족하면 반복문을 더 이상 실행하지 않고 다음 반복문으로 넘어감

0개의 댓글

관련 채용 정보