문제
입력된 수 n 만큼 n행 n열의 형태로 연속으로 출력되는 숙자 사각형을 출력하자..!
- 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
🥺 풀이 :
구구단이나, 별찍기 문제처럼 중첩 반복문을 사용하면된다. (for, while)
public class 숫자사각형 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int sum =0;
for(int i =0; i<N; i++ ) {
for(int j= 0; j<N; j++) {
sum ++;
System.out.print(sum +" ");
}
System.out.println();
}
}
}
<결과>
🥺 더 깔끔하게 보이는 방법 :
for(int i =0; i<N; i++ ) {
for(int j= 0; j<N; j++) {
System.out.printf("%4d", i*N + j+1);
}
System.out.println();
}
'개발 > 알고리즘 기초' 카테고리의 다른 글
[알고리즘 기초] 별찍기 (0) | 2021.04.13 |
---|---|
[알고리즘 기초] 구구단1 (1) | 2021.04.07 |
[알고리즘 기초] 숫자 사각형 만들기2 (0) | 2021.03.31 |
[ 알고리즘 기초 ] 팩토리얼 (0) | 2021.03.29 |
[알고리즘 기초] 피보나치 수열 (0) | 2021.03.27 |