Search code examples
algorithmprocedural-programming

Procedural/imperative programming - Algorithm


Can you please help me understand what ports in r if x = 0,1,2,3

y <-- 0
z <-- 1
r <-- z

while y < x {
Multiply z by 2;
Add z to r;
Increase y; }

Solution

  • In every looping step z is multiplied by 2, so you have the values 2,4,8,16... (or generally 2^n).

    r is initially 1, and if you add z, you get 3,7,15,31 (generally 2^(n+1) - 1)

    For x = 0 the loop will be skipped, so r stays 1

    For x = 1 the loop will... uhm... loop one time, so you get 3 etc.