What will be the output of the pseudocode below and why?

46 views Asked by At

The answer for all three situations is supposedly 3, i dont understand why that is, can someone please explain what is going on and the reasoning behind it, why is the answer 3 for all situations ?

I am new to code, a beginner and need help.

Here is the code

Z [],  T = Z[1]  Z.SIZE>1   T = T+Z[Z.SIZE]  T

What does this process out in the following situations ?
Z[] = [1,2]
Z[] = [1,2,3]
Z[] = [3]

I dont understand the result of the array, i dont understand the logic behind it. I need a simple and easy to understand explanation of the results.

1

There are 1 answers

0
trincot On

That pseudocode looks unusual: all the code is presented on the same line (bad!), no keywords like if or while or for... No clear indication what part is conditional, and what is not. This is atypical in honestly does not pass the standard of what pseudocode is supposed to look like.

I will have a guess at what this code means:

Z [],  T = Z[1]  Z.SIZE>1   T = T+Z[Z.SIZE]  T

...rewriting it in propper pseudocode:

function calculate(Z[1..Z.SIZE]):
    T ← Z[1]
    if Z.SIZE > 1 then:
        T ← T + Z[Z.SIZE]
    return T

This function takes the first element of Z and the last element of Z (if Z has more than one element), and returns the sum of these.

So then we have these expected outputs:

  • calling the function with argument Z = [1,2] will result in 3
  • calling the function with argument Z = [1,2,3] will result in 4
  • calling the function with argument Z = [3] will result in 3