1-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
DECLARE an array
- An array stores many values under one name.
DECLARE Score : ARRAY[1:5] OF INTEGERmakes room for 5 integers.- The numbers
1:5are the first and last index.
中文
DECLARE 声明一个数组
- 数组(array)用一个名字存放许多值。
DECLARE Score : ARRAY[1:5] OF INTEGER为 5 个整数腾出空间。- 数字
1:5是第一个和最后一个索引。
DECLARE Score : ARRAY[1:5] OF INTEGER
Score[1] ← 40
OUTPUT Score[1] // → 40
English
Arrays count from 1
- The first item is
Score[1], the last isScore[5]. - (This is different from Python and JavaScript, which count from 0.)
中文
数组从 1 开始数
- 第一个元素是
Score[1],最后一个是Score[5]。 - (这和 Python、JavaScript 不同,它们从 0 开始数。)
DECLARE Name : ARRAY[1:3] OF STRING
Name[1] ← "Ada"
Name[2] ← "Sam"
OUTPUT Name[2] // → Sam
English
Loop through an array
- A
FORloop visits each index in turn.
中文
遍历数组
FOR循环依次访问每个索引。
DECLARE Score : ARRAY[1:3] OF INTEGER
Score[1] ← 10
Score[2] ← 20
Score[3] ← 30
FOR I ← 1 TO 3
OUTPUT Score[I] // 10, 20, 30
NEXT I
English
Watch out
- The index must stay inside the declared range:
Score[6]is out of[1:5]. ARRAY[1:5]has 5 cells, numbered 1 to 5 — not 0 to 4.
中文
注意
- 索引必须保持在声明的范围内:
Score[6]超出了[1:5]。 ARRAY[1:5]有 5 个格子,编号 1 到 5 —— 不是 0 到 4。
English
Common mistakes
- Declare an array with its bounds:
DECLARE A : ARRAY[1:N] OF INTEGER. - Index only within the declared range.
中文
常见错误
- 声明数组要带边界:
DECLARE A : ARRAY[1:N] OF INTEGER。 - 只在声明的范围内索引。
English
Now you try
- Declare an array, fill it, then read or loop over it.
- Press Check answer to test it.
中文
现在轮到你
- 声明一个数组,填入值,然后读取或遍历它。
- 按检查答案来测试它。
Declare an array A of 3 integers. Store 10, 20, 30 in positions 1, 2, 3, then output A[2] (the answer is 20). · 声明一个含 3 个整数的数组 A。在位置 1、2、3 存入 10、20、30,然后输出 A[2](答案是 20)。
Click Run to see the output here. · 点击“运行”查看此处输出。
The array A holds · 持有 5, 8, 2. Use a FOR loop to add them and output the total (it is 15). · 数组 A 里有 5、8、2。用 FOR 循环把它们相加,输出总和(是 15)。
Click Run to see the output here. · 点击“运行”查看此处输出。
The array A holds · 持有 3, 9, 2, 7. Find the largest value and output it (it is 9). · 数组 A 里有 3、9、2、7。找出最大的值并输出(是 9)。
Click Run to see the output here. · 点击“运行”查看此处输出。