...
Code Block |
---|
language | java |
---|
title | Strings Array in Java |
---|
| int[][] cinema = new int[5][5];
for (int j = 0; j < cinema.length; j++) {
for (int i = 0; i < cinema[j].length; i++) {
cinema[j][i] = 0;
}
} |
| Instead of one bracket used in one dimensional array, we will use two e.g. int[][] to define two-dimensional array.
|
Code Block |
---|
language | py |
---|
title | Strings Array in Python |
---|
| cinema = []
for j in range(5):
column = []
for i in range(5):
Column.append(0)
Cinema.append(column) |
| In Python, we declare the 2D array (list) like a list of lists. First, we create an empty one-dimensional list. Then we generate 5 more lists (columns) using a for loop, fill each list with 5 zeros using a nested loop and add the list to the original list as a new item. The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first. We've just created a table full of zeros. |
...
Code Block |
---|
language | java |
---|
title | Strings in Java | Filling the array in Java |
---|
| cinema[2][2] = 1;
for (int i = 1; i < 4 ; i++) {
cinema[i][3] = 1; // the fourth row
}
for (int i = 0; i < 5 ; i++) {
cinema[i][4] = 1; // the last row
} |
| Code Block |
---|
language | py |
---|
title | Strings Filling the array in Python |
---|
| cinema[2, 2] = 1 # center
for i in range(1, 4): # fourth row
cinema[i][3] = 1
for i in range(5): # the last row
cinema[i][4] = 1 |
| ![](/wiki/download/attachments/117506288/multidimarray.jpg?version=1&modificationDate=1514638600000&api=v2) |
...
Code Block |
---|
language | java |
---|
title | Output in Java |
---|
| int cols = cinema.length;
int rows = cinema[0].length;
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(cinema[i][j]);
}
System.out.println("");
} |
| Code Block |
---|
language | py |
---|
title | Output in Python |
---|
| cols = len(cinema)
rows = 0
if cols:
rows = len(cinema[0])
for j in range(rows):
for i in range(cols):
print(cinema[i][j], end = "")
print() |
| |
Output in both cases would be:
00000
00000
00100
01110
11111