BAEK_2438(별 찍기 - 1)

Max·2022년 9월 5일
0

BAEKJOON

목록 보기
13/21

백준 2438 별 찍기 - 1


- 문제

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제


- 입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.



- 풀이


  • 방법 1
import java.util.Scanner;

public class Main {
	public static void main (String[] args) {
    	Scanner sc = new Scanner(System.in);
        
        int N = sc.nextInt();
        
        for(int i = 1; i <= N; i++) {
        	for(int j = 1; j <= i; j++) {
            System.out.print("*");
        }
       	System.out.println();
      }
    }
  }			            	

이중 for문을 통해 문제를 해결할 수 있다.
for(int i = 1; i <= N; i++)에서 i는 행을 의미한다.
for(int j = 1; j <= i; j++)은 행(i)당 j의 반복 횟수만큼 출력을 할 것이다.
그리고 한 행의 출력이 끝나면 System.out.println()으로 개행을 해준다.
또한 내부 for문에서는 System.out.println가 아닌 System.out.print로 해야 된다.


  • 방법 2
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int N = Integer.parseInt(br.readLine());
        
        for(int i = 1; i <= N; i++) {
        	for(int j = 1; j <= i; j++) {
            	System.out.print("*");
            }
          	System.out.println();
        }
     }
  }

방법 1이랑 같은 이중 for문이지만 BufferedReader을 이용한 방식이다.
입력을 문자열로 받기 때문에 Integer.parseInt()를 통해 int형으로 바꿔준다.

profile
co_der

0개의 댓글

Powered by GraphCDN, the GraphQL CDN