2darrays Quick 2022
2darrays Quick 2022
1 2 3 4 5 6
4 4 7 8 7 5
9 8 7 4 6 2
3 2 4 8 0 4
Declaration
var
arr: array[1..4, 1..6] of Integer = ((1, 2, 3, 4, 5, 6),
(4, 4, 7, 8, 7, 5),
(9, 8, 7, 4, 6, 2),
(3, 2, 4, 8, 0, 4));
end;
end;
Output: 1,2, 3, 4, 5, 6, 4, 4
Read the array top to bottom
end;
end;
Output: 1, 4, 9, 3, 2, 4, 8, 2, 3
Rules
First lets look at the basic structure of the 2D array again.
Left to right
var
row, col: integer;
begin
for row:=1 to 10 do
begin
for col:=1 to 15 do
begin
end;
end;
end;
1. All code is below a BEGIN STATEMENT ie: nothing must be above any BEGIN STATEMENT
when writing a 2d array basic structure.
var
row, col: integer;
begin
for row:=1 to 10 do
// nothing ever here
begin
for col:=1 to 15 do
// nonthing ever here
begin
end;
end;
end;
var
row, col: integer;
begin
for row:=1 to 10 do
// a. what happens at the start of every row
begin
for col:=1 to 15 do
begin
// b. accessing every element of the 2D array
end; // COLS END
arrVending: array [1 .. 10, 1 .. 15] of String = (('C', '', '', '', '', '',
'', '', '', '', '', '', '', '', ''), ('B', 'B', 'B', 'C', 'C', 'C',
'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', ''),
('', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
('C', 'C', '', '', '', '', '', '', '', '', '', '', '', '', ''),
('B', 'B', 'C', 'C', 'B', 'B', 'C', 'C', 'C', 'C', 'B', 'C', 'C', 'B',
''), ('C', 'C', 'B', '', '', '', '', '', '', '', '', '', '', '', ''),
('C', 'B', '', '', '', '', '', '', '', '', '', '', '', '', ''),
('B', 'B', '', '', '', '', '', '', '', '', '', '', '', '', ''),
('C', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
('B', 'C', '', '', '', '', '', '', '', '', '', '', '', '', ''));
for row := 1 to 10 do
begin
sName := arrNames[row];
sString := '';
for col := 1 to 15 do
begin
sString := sString + arrVending[row,col];
end;
redQ4.Lines.Add(sName + #9 + sString);
end;
end;
Review Questions
The lines:
• sName:= arrNames[row];
• sString := ‘’;
are specifically above the for loop for the column. Can you explain why ?
is after the for loop for the column. Is there a reason for this ?
Thirdly, why are the two for loops arranged in the order of for row:= 1 .. and then for col:= 1 and not
the other way around ?