C960 Module 1: Algorithm Structures
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
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?
(b) What is the final value of val.
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
? When
42
When 10
Algorithm 3
1: procedure
2: count=0
, C960: Supplementary Practice Unit 1
3: while (n>1) do
4: count++
5: n = n/10
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?
b. What is the output of the algorithm when x = 1642 and b = 8?
Algorithm 4
1: procedure EXPAND(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)
Page 2 of 8