알고리즘/기타퀴즈

Quiz18, Quiz19 (중첩반복문)

pitang 2021. 8. 26. 23:42
반응형

안녕하세요. pitang입니다.

중첩 반복문에 관해 퀴즈 두 개만 더 보고 다음 시간에는 정렬에 대해 퀴즈를 풀어볼게요!

 

Quiz18

가로, 세로를 입력받아서 직사각형을 출력하세요.

단, 윤곽만 출력하면 됩니다.

(힌트 : 조건을 잘 생각해보고, 사각형 -> 첫행과 마지막행 -> 첫 열과 마지막 열 순으로 생각해보면 됩니다.)

 <console>
가로 > 7
세로 > 5
*******
*        *
*        *
*        *
*******

 

⬇️⬇️⬇️ 정답은 더보기를 눌러주세요 ⬇️⬇️⬇️

 

더보기
public class Quiz18 {

	public static void main(String[] args) {
    
    	Scanner scan = new Scanner(System.in);
        
        System.out.print("가로 > ");
        int a = scan.nextInt();
        System.out.print("세로 > ");
    	int b = scan.nextInt();
        
        for(int i = 1; i <= b; i++) {
        	System.out.println();
            for(int j = 1; j <= a; j++) {
            	if(i == 1 || i == b) {
                	System.out.print("*");
                } else {
                	if(j == 1 || j == a) {
                    	System.out.print("*");
                    } else {
                    	System.out.print(" ");
                    }             
                }
            }
        } 
    }
}

 

Quiz19

정수를 입력받고 2중 for문을 이용하여 입력 받은 수까지 소수들의 합을 출력하세요.

(힌트 : 입력 받은 수까지 반복, 내부 for문에서 외부 for문의 수까지 반복을 생각해보세요.)

<console>
정수를 입력하세요 : 51
51까지 소수들의 합 : 328

 

⬇️⬇️⬇️ 정답은 더보기를 눌러주세요 ⬇️⬇️⬇️

 

더보기
public class Quiz19 {
	
    public static void main(String[] args) {
    
    	Scanner scan = new Scanner(System.in);
    
    	System.out.print("정수를 입력하세요 : ");
    	int num = scan.nextInt();
        int count = 0;
        int sum = 0;
    	
        for(int i = 1; i <= num; i++) {
        	count = 0;
            for(int j = 1; j <= i; j++) {
            	if(i % j == 0) {
                	count++;
                }
            }
            if(count == 2) {
            	sum += i;
            }
        }
    	System.out.println(num + "까지 소수들의 합은 : " + sum);
    	scan.close();
    }
}

count 변수를 초기화 해주는 곳이 중요하다. 

i 가 for문을 돌때마다 count = 0;으로 초기화해줘야 한다.

 

감사합니다.

 

*m1맥북을 사용 중입니다.*

728x90
반응형