2-D arrays
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 มิติคือตาราง
- แอลเลย์ 2 มิติ มีแถวและคอลัมน์, เหมือนตาราง
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
Two indexes: row, column
- Use
G[row, column]to reach one cell. - The first cell is
G[1,1].
Two indexes: row, column
- ใช้
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
Nested FOR over a grid
- An outer loop walks the rows; an inner loop walks the columns.
Nested FOR over a grid
- L For loop walk the rows; an inner loop walk the columns.
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
Watch out
- The order is
G[row, column]— row first, then column. NEXT R
ระวัง
- The order is
G[row, column]— row first, then column. NEXT R
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.
ข้อผิดพลาดที่พบบ่อย
- A 2-D array is
ARRAY[1:r, 1:c]; use two indexes. - ลูปภายนอกเดินผ่านแถว ลูปภายในเดินผ่านคอลัมน์
Now you try
- Use two indexes, or nested
FORloops. - Press Check answer to test it.
ลองดูเลย
- Use two indexes, or nested
FORloops. - กด Check answer เพื่อทดสอบ
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 ให้แต่ละเซลล์เก็บ row × column, แล้วรวมทุกเซลล์ด้วยลูปซ้อนและแสดงผลรวม (คือ 18)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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 รับค่าหลายค่าคั่นด้วยcomma
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่