Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
The nine squares of a board are input row by row: X, O, O, then X, X, X, then O, a dot for an empty square, and X.
DECLARE Board : ARRAY[1:3, 1:3] OF CHAR
DECLARE Row : INTEGER
DECLARE Column : INTEGER
DECLARE Count : INTEGER
DECLARE Line : INTEGER
// the nine squares are input row by row
FOR Row ← 1 TO 3
FOR Column ← 1 TO 3
INPUT Board[Row, Column]
NEXT Column
NEXT Row
Line ← 0
FOR Row ← 1 TO 3
Count ← 0
FOR Column ← 1 TO 3
IF Board[Row, Column] = 'X'
THEN
Count ← Count + 1
ENDIF
NEXT Column
IF Count = 3
THEN
Line ← Row
ENDIF
NEXT Row
Count ← 0
FOR Row ← 1 TO 3
IF Board[Row, Row] = 'X'
THEN
Count ← Count + 1
ENDIF
NEXT Row
OUTPUT Line, " ", CountWhat is output? What do the two numbers mean?
DECLARE Name : ARRAY[1:Rows, 1:Columns] OF TYPE has rows times columns elements. An element is Name[Row, Column]. Nested loops visit every element: the outer loop for the rows, the inner loop for the columns. A row total is set to zero inside the outer loop, before the inner one.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The rows. Row 1 has 1 X, row 2 has 3, row 3 has 1. Only row 2 is full, so Line is 2.
Step 2. The diagonal. Board[1, 1], Board[2, 2] and Board[3, 3] are X, X and X, so Count is 3.
Answer: the output is 2 3. X has a full row in row 2, and also the whole diagonal.
Watch out. Count is set back to 0 at the start of each row, and again before the diagonal check. Without that, it would keep counting from the rows before.
Log in to join the discussion.
Loading…