Module 1: Algorithm Structures
1 With the pseudo-code below, determine the final value of sum when n=23.
Algorithm 1
1: procedure
2: sum = 0
3: for (i=2, i<n, i=i+3) do
4: if i mod 2 == 0
5: sum = sum + i
Solution: sum = 44
With i starting at 2 and incrementing by 3 every iteration, i will iterate through the values 2, 5, 8, 11, 14,
17, and 20. The if statement means sum will only be updated when i is even, adding 2, 8, 14, and 20 for
a total of 44
2 Use the pseudo-code below to answer the following question.
(a) Without working through the pseudo-code, how many times with val be updated in Line 7?
Solution: 24
The loop in line 5 will iterate 4 times. The loop in line 6 will iterate 6 times. Since they are nested,
we multiply and val will be updated 4 · 6 = 24 times.
(b) What is the final value of val.
Solution: val = 210
The algorithm loops through all possible combinations of x and y, multiplies them, and adds them to
val. In the end, we get
1·1+1·2+1·3+1·4+1·5+1·6 +
2·1+2·2+2·3+2·4+2·5+2·6 +
3·1+3·2+3·3+3·4+3·5+3·6 +
4 · 1 + 4 · 2 + 4 · 3 + 4 · 4 + 4 · 5 + 4 · 6 = 210
Algorithm 2
1: procedure
2: dFour = [1, 2, 3, 4]
3: dSix = [1, 2, 3, 4, 5, 6]
4: val = 0
5: for (x in dFour) do
6: for (y in dSix) do
7: val = val + x·y
Suggestions or errors? Monday 13th September, 2021
Email the IT Math Team
, C960: Supplementary Practice Unit 1
3 Using the pseudo-code below, what is the ending value for count when n = 100? When n = 10,000?
When n = 1042 ?
Algorithm 3
1: procedure
2: count=0
3: while (n>1) do
4: count++
5: n = n/10
Solution:
When n = 100, count will end at 2.
When n = 10,000, count will end at 4.
When n = 1042 , count will end at 42.
4 This question assumes familiarity with modular arithmetic discussed in Unit 2. In the pseudo-code below,
Line 7 performs string addition (concatenation), for example:
"a" + "b" = "ab". Even if the addends look like numbers, it will still do string addition:
"2" + "3" = "23". Answer the questions below.
a. What is the output of the algorithm when x = 99 and b = 2?
Solution: Context for writing a number in base b is presented in Module 6 of Unit 2.
Expand(99, 2) = "1100011"
b. What is the output of the algorithm when x = 1642 and b = 8?
Solution: Expand(1642, 8) = "3152"
Algorithm 4
1: procedure E X P A N D (x, b)
2: Input: integers x and b
3: Output: outVal, x written in base b
4:
5: outVal = an empty string
6: while (x>0) do
7: outVal = string(x mod b) + outVal
8: x = x div b
9: return(outVal)
Suggestions or errors? Page 2 of 9 Monday 13th September, 2021
Email the IT Math Team