Thinking Logically 1 Done
Thinking Logically 1 Done
1. Use the trace table below to help you answer (a), (b) and (c) below.
What would be the values of integer variables x, y and z after execution of these statements
if the initial values of x and y are:
(a) 2 and 7
(b) -4 and -4
(c) 27 and 3
Trace table
z = x x y z
IF x = y THEN
x = x * x 2 7 2
y = (x + y) / 2
ELSE a) 49 47
IF x < y THEN
y = y * y
z = y - x
-4 -4 -4
ELSE b)
IF x > 0 THEN 16 -4
z = x/y
ENDIF 23 3 23
ENDIF
y = 200 c) 23 3 23/3
ENDIF
OUTPUT x, y, z
2. Use a trace table to determine the output from the following algorithm.
x = 5
k = 10 x k sum OUTPUT
sum = 45
5 10 45
WHILE sum < 75
sum = sum + k 5 15 55 10
OUTPUT k 20 70 15
k = k + x
90
ENDWHILE
OUTPUT sum 90
1
903546631.docx Name: Reinas P
3. Study the following algorithm and fill in the trace tables below to discover what it does.
y=2
z=1
OUTPUT ("Please enter a positive integer: ")
x = USERINPUT
WHILE z <> 0 # while z not == 0 THEN
z = x mod y # z is the remainder of x/y
IF z <> 0 THEN
y=y+1
ENDIF
ENDWHILE
IF x = y
print (x, " is in category 1") #Prime Number
ELSE
print (x, " is in category 2") # Compsoite numbers
ENDIF
(i) If the user inputs the integer 25, what is (ii) If the user enters the integer 7, what is
output? Category 2 output? Category 1
x y z x y z
25 2 1 7 2 1
25 3 1 7 3 1
25 4 1 7 4 1
25 5 0 7 5 1
7 6 1
7 7 0
(iii) What are “category 1” and “category 2”? What is the purpose of the program?
C1 = prime numbers c2 = non prime numbers
(iv) Suggest ways in which the program could be made easier to understand.
The program should have added comments to make it more understandable and
replacing the category 1 with prime number. and category 2 with composite number
(v) This is a “brute force” algorithm. Suggest how the algorithm could be made more
efficient.
2
903546631.docx Name: Reinas P