Professional Documents
Culture Documents
Topic 4 WS1 - Ans
Topic 4 WS1 - Ans
1. Assume an array ARR stores integers in it. Write pseudocodes for the following:
a) To calculate the sum of all even numbers in the array.
len = ARR.length
sum = 0
loop index from 0 to len-1
if (ARR[index] mod 2 = 0) then
sum = sum + ARR[index]
end if
end loop
output(sum)
8 Sep. 23 Page 1 of 4
d) To store all the elements of ARR into a collection COL.
len = ARR.length
loop index from 0 to len-1
COL.addItem(ARR[index])
end loop
2. Assume a collection COL holds integers in it. Write pseudocodes for the
following:
a) To calculate the sum of all odd numbers in the collection.
COL.resetNext()
sum = 0
loop while (COL.hasNext() = true)
d = COL.getNext()
if (d mod 2 = 1) then
sum = sum + d
end if
end loop
output(sum)
8 Sep. 23 Page 2 of 4
d) To store all the elements of COL into an array ARR.
COL.resetNext()
index = 0
loop while (COL.hasNext() = true)
d = COL.getNext()
ARR[index] = d
index = index + 1
end loop
3. Write pseudocode to sort an integer array NUM using:
a) Bubble sort
N = NUM.length
loop x from 0 to N-2
loop y from 0 to N-I-1
if (NUM[y] > NUM[y+1]) then
temp = NUM[y]
NUM[y] = NUM[y+1]
NUM[y+1] = temp
end if
end loop y
end loop x
b) Selection sort
N = NUM.length
loop I from 0 to N - 2
BIG = NUM[I]
POS = I
loop J from I + 1 to N - 1
if (NUM[J] > BIG) then
BIG = NUM[J]
POS = J
end if
end loop J
if (POS ≠ I) then
T = NUM[I]
NUM[I] = NUM[POS]
NUM[POS] = T
end if
end loop I
8 Sep. 23 Page 3 of 4
4. Assume an array MARKS stores marks of students in a test.
a) Write pseudocode using linear search to check if a mark D is found in the
array or not.
N = NUM.length
FOUND = FALSE
loop I from 0 to N - 1
if (NUM[I] = D) then
FOUND = TRUE
output("Element found in Index " + I)
I = N //to come out of the loop
end if
end loop
8 Sep. 23 Page 4 of 4