본문 바로가기

알고리즘 문제

(Java) 숫자 사각형

숫자 n이 입력 값으로 들어간다.

출력처럼 값이 나와야 한다.

 

숫자 사각형_01:

더보기
package alg;

public class int_square_01 {
	public static void main(String[] args) {
		
		
		int n = 4;
		int num = 1;
		
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				System.out.printf("%4d", num);
				num++;
			}
			System.out.println();
		}
	}

}

 

n = 입력 값;

 

num = 출력할 값;

for(){   == 행

for(){  == 열

System.out.printf() == 한 줄에 출력 ////   "%4d" == 숫자 앞에 4개의 공백을 넣음

num++   == num을 1씩 증가시킴

}

 System.out.prinln(); == 줄 넘김

}

 

출력:

   1   2   3   4
   5   6   7   8
   9  10  11  12
  13  14  15  16

 

숫자 사각형_02:

더보기
package alg;

public class int_square_02 {
	public static void main(String[] args) {
		
		int n = 4;
		
		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] = i * n + j + 1;
				}
			}else {
				for(int j = n - 1; j >= 0; j--) {
					arr[i][j] = i * n + n - j;
				}
				
			}
		}
		
		
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				System.out.printf("%4d" , arr[i][j]);
			}
			System.out.println();
		}
		
	}

}

 

n = 입력 값;

if(n = 4)

 

arr = 값을 넣을 배열

 

for(){ == 행

if(){  == 짝수 일 때 

for(){ == 열

arr [ i ][ j ]  = i * n + j + 1   == arr의 짝수 행 첫 번째부터 (0, 2,..) * 4 + (0 ~ 3) + 1

}

}else{ == 짝수가 아닐 때

for(){ ==열

arr[ i ][ j ]  = i * n + n - 1   == arr의 홀수 행 뒤부터 (1, 3,..) * 4 + 4 -1

}

}

}

 

출력:

   1   2   3   4
   8   7   6   5
   9  10  11  12
  16  15  14  13

 

 

숫자 사각형_03:

더보기
package alg;

public class int_square_03 {
	public static void main(String[] args) {
		
		int n = 4;
		
		int[][] arr = new int[n][n];
		
		int num = 1;
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				arr[j][i] = num;
				num++;
			}
		}
		
		
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				System.out.printf("%3d", arr[i][j]);
			}
			System.out.println();
		}
	}

}

 

n = 입력 값

 

arr = 값을 넣을 배열

 

num = 배열에 넣을 값

 

for(){ == 열

for(){ == 행

arr[ j ][ i ] = num    == arr의 각 열의 행에 num을 넣음

num++; == num을 1씩 증가 시킴

}

}

출력:

   1   5   9  13
   2   6  10  14
   3   7  11  15
   4   8  12  16

 

 

숫자 사각형_04:

더보기
package alg;

public class int_square_04 {
	public static void main(String[] args) {
		
		
		int n = 4;
		
		int[][] arr = new int[n][n];
		
	
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				arr[j][i] = (i + 1) * (j + 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();
		}
	}

}

 

n = 입력 값

if(n = 4)

 

arr = 값을 넣을 배열

 

for(){ == 열

for(){ == 행

arr [ j ][ i ] = ( i + 1 ) * ( j + 1 )    ==

arr의 첫 번째 열 행에 (0 + 1)  *  ((0 ~ 3) + 1)

arr의 두 번째 열 행에 (1 + 1)  *  ((0 ~ 3) + 1)

arr의 세 번째 열 행에 (2 + 1)  *  ((0 ~ 3) + 1)

arr의 네 번째 열 행에 (3 + 1)  *  ((0 ~ 3) + 1)

}

}

출력:

   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16