문제 2741 -JAVA
자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.
내가 틀린 코드1
package dailystudy;
import java.util.Scanner;
public class q_1001 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N;
N = s.nextInt();
s.close();
for(int i = 0 ; i<N; i++) {
System.out.println(N);
}
}
}
처음 추론한 틀린 이유:
출력 값을 i로 해야하는데 N을 출력했기 때문이다.
그로인한 출력 결과
내가 틀린 코드2
package dailystudy;
import java.util.Scanner;
public class q_1001 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N;
N = s.nextInt();
s.close();
for(int i = 0 ; i<N; i++) {
System.out.println(i);
}
}
}
두번째 추론한 틀린 이유:
출력값과 배열의 번호를 착각했다. 문제는 1부터 출력해야한다.
그로인한 출력 결과
정답
package dailystudy;
import java.util.Scanner;
public class q_1001 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N;
N = s.nextInt();
s.close();
for(int i = 1 ; i<= N; i++) {
System.out.println(i);
}
}
}