본문 바로가기

JAVA

구구단 숫자 입력받아 출력하기 자바 - 전체/짝수/홀수단 (백준 2739번)

< WHILE문을 이용하여 특정 단 출력하기 (백준 2739번 구구단 정답코드) >

정수 n을 입력받은 뒤, n단을 출력하는 프로그램(1≤N≤9)

import java.util.*;

class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        int m = 1;
        
        while(m<10){
            int result = n*m;
            System.out.println(n+" * "+m+" = "+result);
            m++;
        }
    }
}

 

< 입력 없이 FOR문을 이용하여 구구단 1~9단 전체 출력 >

import java.util.*;

class Main{
    public static void main(String[] args){
        for(int i = 1; i<10; i++){
            for(int j = 1; j<10; j++){
                int result = i*j;
                System.out.println(i+" * "+j+" = "+result);
            }
            System.out.println(); //단 사이에 한 줄 띄우기
        }
    }
}

 

< 짝수단 또는 홀수단만 출력하고 싶은 경우>

홀수단일 경우 아래 코드처럼 inner loop에서 한 단을 돈 후 i를 1씩 더 늘려서 한 단을 건너뛰면 된다. 

짝수단만 출력하고 싶은 경우에는 아래 코드에서 시작 단인 i를 2로 초기화하면 된다. (int i=2로 초기화)

import java.util.*;

class Main{
    public static void main(String[] args){
        for(int i = 1; i<10; i++){
            for(int j = 1; j<10; j++){
                int result = i*j;
                System.out.println(i+" * "+j+" = "+result);
            }
            System.out.println(); //단 사이에 한 줄 띄우기
            i++;	//i를 한 번 더 증가시켜 한 단을 건너뜀
        }
    }
}