입력
자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.
출력
첫째 줄에 100,000보다 작거나 같은 자연수 N이 주어진다.
[문제 풀이]
1. 1부터 출력시킬 자연수 n을 입력받는다.
// #1. Scanner 사용 (31640 KB / 1044 ms )
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// #2. BufferReader 사용
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
2. for문을 이용하여 자연수를 1부터 n까지 n번 출력시킨다.
case1) 이 때 for문의 i는 0부터 시작하므로 출력문에서는 i+1을 출력시킨다.
case2) 위의 방법 말고 for문에서 i를 1부터 출력시키는 방법도 있다.
// case1
for(int i=0; i<n; i++) {
System.out.println(i+1);
}
// case2
for(int i=1; i<n+1; i++) {
System.out.println(i);
}
# 전체 코드
package com.algorithm.chapter3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ch3_5 {
public static void main(String[] args) throws IOException {
// #1. Scanner 사용 (31640 KB / 1044 ms )
// Scanner sc = new Scanner(System.in);
// int n = sc.nextInt();
// #2. BufferReader 사용 ( 29732 KB / 884 ms)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for(int i=0; i<n; i++) {
System.out.println(i+1);
}
}
}
'STUDY > 백준알고리즘' 카테고리의 다른 글
[11021:JAVA] A+B - 7 (0) | 2022.04.04 |
---|---|
[2742:JAVA] 기찍N (0) | 2022.04.01 |
[15552:JAVA] 반복문 > 빠른 A+B (0) | 2022.03.30 |
[8393:JAVA] 반복문 > 합 (0) | 2022.03.28 |
[10950:JAVA] 반복문 > A+B -3 (0) | 2022.03.27 |