Worksheet 2 Writing and following algorithms
Unit 3 Software development
Task 1
1. What will be the output from the algorithm below if the user inputs “Hi, Jo!”
Explain briefly the purpose of the algorithm.
function encrypt(message, shift)
message = lowercase(message)
encryptedMessage = ""
for x in message
if x in “abcdefghijklmnopqrstuvwxyz”
num = ord(x) # convert to ASCII value
num = num + shift
if num > ord(“z”) # wrap if necessary
num = num – 26
endif
char = chr(num) # convert back to character
encryptedMessage = encryptedMessage + char
else
encryptedMessage = encryptedMessage + x
endif
next x
return encryptedMessage
endfunction
# main program
shift = 3
msg = input(“Enter your message: ”)
encryptedMessage = encrypt(msg, shift)
print(“The encrypyted message is: ”, encryptedMessage)
1
Worksheet 2 Writing and following algorithms
Unit 3 Software development
Task 2
2. An array marks is defined as follows: marks[15, 18, 14, 9, 16, 12, 10]
A pseudocode algorithm for an algorithm is given below.
items = len(marks)
for i = 0 to items - 2
for j = 0 to (items - i - 2)
if marks[j] > marks[j+1]
temp = marks[j]
marks[j] = marks[j+1]
marks[j+1] = temp
endif
next j
next i
print (marks)
One pass is made through the outer loop of the algorithm.
Complete the trace table below to show how the contents of the array changes.
marks
items i j temp
[0] [1] [2] [3] [4] [5] [6]
15 18 14 9 16 12 10
7 0 0 15 18 14 9 15 12 10
1 15 14 18 9 15 12 10
What is the name of the algorithm?
2
Worksheet 2 Writing and following algorithms
Unit 3 Software development
3. Complete the trace table to determine the purpose of the following algorithm.
Test it with input 11 and 5.
x = input ("Enter the first integer: ")
y = input ("Enter the second integer: ")
z = 0
while x > 0
if x mod 2 == 1 then
z = z + y
endif
x = x div 2
y = y * 2
endwhile
print ("Answer =", z)
x y z x> 0 x mod 2 == 1 output
11 5 0 True True