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

[014] 숫자 사각형 출력하기(행 자릿수 만큼 증가)

by 은z 2021. 5. 26.

문제

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

ex) n = 3

1 2 3

2 4 6

3 6 9

 

- 중첩반복문 이용, 배열

 

보완할 점

 

소스코드

public class Algorithm13 {

	public static void main(String[] args) {
		int n = 5;
		int snum = 1;
		int[][] arr = new int[n][n];
		
		for(int i = 0; i < n; i++) {
			snum = i + 1; // snum 값 변경
			for(int j = 0; j < n; j++) {
				arr[i][j] = snum; 
				snum = snum + (i + 1);  
			}
		}
		
		for(int i = 0; i < n; i++) {
 			for(int j = 0; j < n; j++) {
 				System.out.printf("%4d", arr[i][j]);
 			}
 			System.out.println();
 		}
	}
}

 

댓글