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

[012] 숫자 사각형 출력하기(거꾸로)

by 은z 2021. 5. 26.

문제

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

ex) n = 3

1 2 3

6 5 4

7 8 9

 

- 중첩반복문 이용, 배열

 

보완할 점

- 처음에 배열을 사용하지 않고 풀어서 해결방법을 찾기 어려웠음

- 배열에 값을 넣는 for문과 출력을 위한 for문을 분리하는 것 기억하기

 

소스코드

public class Algorithm11 {

	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++) {
			
			if(i % 2 ==0) {
				for(int j = 0; j < n; j++) {
					arr[i][j] = snum + 1; // 1 2 3 4 
					snum = arr[i][j];
				}
			}
			else {
				for(int j = n-1; j >= 0; j--) {
					arr[i][j] = snum + 1; // 5 6 7 8
					snum = arr[i][j];
				}
			}
		}
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}
	}

}

댓글