May I trouble anyone to help me understand how this sort of pseudocode algorithm works and how it arrived at the correct answer? Any help would be greatly appreciated.
These are questions with traps in them. It is testing whether you really look closely to every aspect of the code for both question 6 and question 7:
The first code can be expressed in JavaScript as follows:
function Find2(s, n) {
let EleFound = s[0]
for (let i = n-1; i >= 0; i--) {
if (s[i] > EleFound) {
EleFound = i
}
}
return EleFound
}
let result = Find2([3, 15, 7, 9], 4);
console.log(result);
When you run it, you'll see it outputs 0. Once you see it, it is obvious, but the line EleFound = i
is assigning the index, not s[i]
! And as the index i
is decreasing to zero, and s[1]
is greater than the initial value of EleFound
, EleFound
will get the value 1, not 15! And in the last iteration it will get assigned 0, because s[0]
is greater than 1(!).
The second code can be run as:
function AddMul5(A, n) {
let sum = A[0]
for (let i = 1; i <= n-1; i++) {
sum = sum + i
}
return sum
}
let result = AddMul5([3, 5, 7, 9], 5);
console.log(result);
The output is 13. Did you spot the trap here? It is quite similar...
Hints:
which values from
A
are used in this sum?
Is
A[1]
used at all?