Question 1 Report
Study the following pseudocode.
FUNCTION Absolute(N : INTEGER) RETURNS INTEGER
IF N < 0 THEN
RETURN -N
ELSE
RETURN N
ENDIF
ENDFUNCTION
FUNCTION Distance(X1 : INTEGER, Y1 : INTEGER, X2 : INTEGER, Y2 : INTEGER) RETURNS INTEGER
RETURN Absolute(X1 - X2) + Absolute(Y1 - Y2)
ENDFUNCTION
PROCEDURE FindNearest(TargetX : INTEGER, TargetY : INTEGER)
DECLARE Points : ARRAY[1:4, 1:2] OF INTEGER
DECLARE NearestDist : INTEGER
DECLARE NearestIdx : INTEGER
DECLARE Dist : INTEGER
DECLARE i : INTEGER
Points[1,1] ← 3 Points[1,2] ← 7
Points[2,1] ← 1 Points[2,2] ← 2
Points[3,1] ← 8 Points[3,2] ← 4
Points[4,1] ← 5 Points[4,2] ← 6
NearestDist ← Distance(TargetX, TargetY, Points[1,1], Points[1,2])
NearestIdx ← 1
FOR i ← 2 TO 4
Dist ← Distance(TargetX, TargetY, Points[i,1], Points[i,2])
IF Dist < NearestDist THEN
NearestDist ← Dist
NearestIdx ← i
ENDIF
NEXT i
OUTPUT "Nearest point: (", Points[NearestIdx,1], ",", Points[NearestIdx,2], ") at distance ", NearestDist
ENDPROCEDURE
CALL FindNearest(4, 5)(a) State the value of Absolute(-7). [1]
(a) Absolute(-7) returns 7. [1]
The function checks if N < 0. Since -7 < 0 is TRUE, it returns -(-7) = 7. The Absolute function strips the sign from a negative number, returning its magnitude.
Everything you need to excel in your exams