Java

[Java] 점프 투 자바 연습문제 04장 제어문

kyra 2022. 9. 24. 12:55

 

2. while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자.

public class HelloJava {
    public static void main(String[] args) {
        int n = 1, sum = 0;
        while (n <= 1000) {
            if (n % 3 == 0) {
                sum += n;
                n++;
            }
            else{
                n++;
                continue;
            }
        }
        System.out.println(sum);
    }
}

 

 

public class HelloJava {
    public static void main(String[] args) {
        int i = 0;
        while(true){
            i += 1;
            if (i > 5){
                break;
            }
            for (int j = 0 ; j<i ; j++){
                System.out.print("*");
            }
            System.out.println(""); //출력 후 줄바꿈
        }
    }
}

i가 1일때 j = 1 --> *출력

i가 2일때 j = 0, 1, 2 --> **출력

i가 3일때 j = 0, 1, 2, 3 --> ***출력

i가 4일때 j = 0, 1, 2, 3, 4 --> ****출력

i가 5일때 j = 0, 1, 2, 3, 4, 5 --> *****출력


 

public class HelloJava {
    public static void main(String[] args) {
        int i = 0;
        for (i = 1; i <= 100; i++) {
            System.out.println(i);
        }
    }
}

 


public class HelloJava {
    public static void main(String[] args) {
        int[] marks = {70, 60, 55, 75, 95, 90, 80, 80, 85, 100};
        int total = 0;
        for (int mark:marks) { //for each 구문 활용
            total += mark;
        }
        float average = total / marks.length;  // total/marks.length는 정수이므로 실수로 캐스팅
        System.out.println(average);
    }
}