2-D arrays · 二维数组
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A 2-D array is a grid
- A 2-D array has rows and columns, like a table.
ARRAY[1:2, 1:3]means 2 rows and 3 columns.
中文
二维数组是一个网格
- 二维数组(2-D array)有行和列,就像一张表格。
ARRAY[1:2, 1:3]表示 2 行 3 列。
DECLARE G : ARRAY[1:2, 1:3] OF INTEGER
G[1,1] ← 5
OUTPUT G[1,1] // → 5
English
Two indexes: row, column
- Use
G[row, column]to reach one cell. - The first cell is
G[1,1].
中文
两个索引:行、列
- 用
G[row, column]取出一个格子。 - 第一个格子是
G[1,1]。
DECLARE G : ARRAY[1:2, 1:2] OF INTEGER
G[1,2] ← 7
G[2,1] ← 9
OUTPUT G[1,2] // → 7
English
Nested FOR over a grid
- An outer loop walks the rows; an inner loop walks the columns.
中文
用嵌套 FOR 遍历网格
- 外层循环走行;内层循环走列。
DECLARE G : ARRAY[1:2, 1:3] OF INTEGER
DECLARE R, C : INTEGER
FOR R ← 1 TO 2
FOR C ← 1 TO 3
G[R, C] ← R * C
NEXT C
NEXT R
FOR R ← 1 TO 2
FOR C ← 1 TO 3
OUTPUT G[R, C]
NEXT C
NEXT R
English
Watch out
- The order is
G[row, column]— row first, then column. NEXT R
中文
注意
- 顺序是
G[row, column]—— 先行,再列。 NEXT R
English
Common mistakes
- A 2-D array is
ARRAY[1:r, 1:c]; use two indexes. - The outer loop walks the rows, the inner the columns.
中文
常见错误
- 二维数组是
ARRAY[1:r, 1:c];用两个索引。 - 外层循环走行,内层走列。
English
Now you try
- Use two indexes, or nested
FORloops. - Press Check answer to test it.
中文
现在轮到你
- 使用两个索引,或嵌套
FOR循环。 - 按检查答案来测试它。
Declare a 2×2 grid G. Store 1 in · 入 G[1,1] and 4 in · 入 G[2,2], then output their sum (it is 5). · 声明一个 2×2 的网格 G。把 1 存进 G[1,1],4 存进 G[2,2],然后输出它们的和(是 5)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Fill a 2×3 grid G so each cell holds row × column, then add up every cell with nested loops and output the total (it is 18). · 填一个 2×3 的网格 G,使每个格子存 行 × 列,然后用嵌套循环把每个格子加起来,输出总和(是 18)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a loop to output a 3-by-3 square of stars: three lines, each with three *. OUTPUT takes several values separated by commas. · 用循环输出一个 3×3 的星号方块:三行,每行三个 *。OUTPUT 可以用逗号分隔多个值。
Click Run to see the output here. · 点击“运行”查看此处输出。