2차원 배열

Dec 18, 2023
2차원 배열
💡
배열을 행과 열의 2차원으로 나열한 구조
 
배열의 선언 int [][] s = new int[3][5] ;
 
notion image
s 라는 배열은 3행 x 5열의 구조를 가진다.
2차원 배열도 연속적인 공간이 필요하기 때문에 값이 정해지면 변경되지 않는다.
 

2차원 배열의 초기화

int[][] seats = { {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 0} };
 
seats[3][10] 의 2차원 배열이다.
 
이 배열에서 1의 개수를 세어보자.
 
우선 첫 번째 행부터 세어보자.
 
int[] seat1 = seats[0]
 
2차원 배열 중 0번 행을 선언했다.
 
public static void main(String[] args) { int[][] seats = { {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, // {0, 0, 0, 0, 0, 0, 1, 1, 1, 0}}; int[] seat1 = seats[0]; // int count = 0; for (int i = 0; i < seat1.length; i++) { count = count + seat1[i];// } System.out.println("첫번째 행의 1의 수는 :" + count);
notion image
 
이제 3번째 행까지 복붙하자.
 
public class TheaterSeats { public static void main(String[] args) { int[][] seats = { {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 0}}; int sum = 0; int count = 0; int[] seat1 = seats[0]; int[] seat2 = seats[1]; int[] seat3 = seats[2]; count = 0; for (int i = 0; i < seat1.length; i++) { count = count + seat1[i];// } System.out.println("첫번째 행의 1의 수는 :" + count); sum = sum + count; count = 0; for (int i = 0; i < seat2.length; i++) { count = count + seat2[i];// } System.out.println("두번째 행의 1의 수는 :" + count); sum = sum + count; count = 0; for (int i = 0; i < seat3.length; i++) { count = count + seat3[i];// } System.out.println("세번째 행의 1의 수는 :" + count); sum = sum + count; System.out.println("전체 1의 개수는 :" + sum); } }
notion image
 
이제 seats1,2,3 으로 나웠던 값을 원래의 배열로 표시하자.
각 row 로 만들었고, 각 반복문이 일치하도록 변수 row는 -1 부터 시작해서 반복문 시작 전에 1씩 증가하도록 만들었다.
 
public class TheaterSeats { public static void main(String[] args) { int[][] seats = { {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 0}}; int sum = 0; int count = 0; int row = -1; row++; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 1의 수는 :" + count); sum = sum + count; row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i];// } System.out.println(row + "번째 행의 1의 수는 :" + count); sum = sum + count; row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i];// } System.out.println(row + "번째 행의 1의 수는 :" + count); sum = sum + count; System.out.println("전체 1의 개수는 :" + sum); } }
 
이제는 반복문이 완전히 같아졌다. 이중 반복문으로 합칠 수 있을 것 같다.
 
public class TheaterSeats { public static void main(String[] args) { int[][] seats = { {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 0} }; int count = 0; for (int row = 0; row < seats.length; row++) { for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 1의 수는 :" + count); } System.out.println("1의 수는 :" + count); } }
notion image
 
 
Share article
RSSPowered by inblog