본문 바로가기
알고리즘 문제연습/기초 알고리즘

[013] 숫자 사각형 출력하기(세로로)

by 은z 2021. 5. 26.

문제

- 입력된 수만큼 n행 n열의 형태로 연속으로 출력되는 숫자 사각형을 구현하세요

ex) n = 3

1 4 7

2 5 8

3 6 9

 

- 중첩반복문 이용, 배열

 

보완할 점

 

소스코드

public class Algorithm12 {

	public static void main(String[] args) {
		int n = 5;
		int snum = 0;
		int[][] arr = new int[n][n];
		
 		for(int i = 0; i < n; i++) {
 			snum = i + 1; //
			for(int j = 0; j < n; j++) {
				arr[i][j] = snum; 
				snum = snum + n; 
			}
		}
 		
 		for(int i = 0; i < n; i++) {
 			for(int j = 0; j < n; j++) {
 				System.out.print(arr[i][j] + " ");
 			}
 			System.out.println();
 		}
	}
}

댓글