콘텐츠로 이동

4단원 숙제 정답: 조건문과 반복문

문제 1

출력은 B다. 세 if는 모두 독립이라 60, 70, 80 조건이 차례로 모두 참이 된다. else if 사슬이어도 이 코드의 순서가 낮은 경계부터라면 첫 조건에서 D가 되어 결과는 D다. 보통 높은 경계부터 else if를 작성한다.

문제 2

age == 13이 어느 조건에도 맞지 않아 adult가 된다. 다음처럼 고친다.

if (age < 13) group = "child";
else if (age < 20) group = "teen";
else group = "adult";

문제 3

winter 다음 spring이 출력된다. case 2break가 없어 다음 case로 흘러간다.

case 12: case 1: case 2:
    System.out.println("winter"); break;
case 3: case 4: case 5:
    System.out.println("spring"); break;

문제 4

1 4 7 10

몸체는 4번 실행된다.

문제 5

int sum = 0;
for (int i = 1; i <= 30; i++) {
    if (i % 3 == 0 && i % 5 != 0) sum += i;
}
System.out.println(sum); // 105

문제 6

0, break, += 순서다.

if (n == 0) break;
if (n > 0) sum += n;

문제 7

1 2 4 5

3과 6은 continue로 출력하지 않고, 7에서 break가 실행되어 반복문 자체가 끝난다.

문제 8

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Age: "); int age = sc.nextInt();
        System.out.print("Hour: "); int hour = sc.nextInt();
        int fee;
        if (age < 13) fee = 4000;
        else if (age <= 19) fee = 7000;
        else fee = 10000;
        fee = hour >= 17 ? fee - 2000 : fee;
        fee = fee < 0 ? 0 : fee;
        System.out.println("Fee: " + fee);
    }
}