2-D arrays · مصفوفات 2-D
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.
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].
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.
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
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.
Now you try
- Use two indexes, or nested
FORloops. - Press Check answer to test it.
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 بحيث تحتوي كل خلية على row × column، ثم اجمع كل خلية باستخدام حلقات متداخلة وأخرج المجموع (وهو 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. · اضغط تشغيل لرؤية المخرجات هنا.