1
  function A(a, b) {
     return a[b] * b;
   }
  function B(a) {

     var x = 0;
     for (var i=5; i>0; i--)
     x += A(a, i);

     return x;
  }
      var aValues = [3,5,9,8,7,1];
      var y = B(aValues);

Would the answer be: B(1) B(3) B(5) B(7) B(8) B(9) ? Im lost be any push in the right direction would be appreciated.

7
  • What language is that and where does the code come from? Commented Dec 15, 2012 at 20:26
  • 2
    I'm guessing this is Javascript? And by answer, do you mean the value of y? Because if that was the case, y should just be an integer... Commented Dec 15, 2012 at 20:32
  • jsfiddle.net/E7dXP try this in a fiddle :) Commented Dec 15, 2012 at 20:44
  • "The answer" is 42. Or what's the question? Commented Dec 15, 2012 at 20:51
  • i think it is javascript and i think the answer is 80, I got some help, it should be a=aValues and B is i. So it would work out as 1*5 x=5, then 4*7 then x=5+28, 3*8 then x=33+24, 2*9 then x=57+18, 1*5 then x=75+5, x=80 so var y=80? Im sorry for the lack of information given. Commented Dec 16, 2012 at 1:47

1 Answer 1

3

After the execution y is 80. The complete array is passed to B(). The loop in B() iterates over the last 5 elements of aValues. Arrays in Javascript start at index 0, so the loop i=5; i>0; i-- never touches the array element with index 0

Function a() then multiplies the current item with the current index and returns the result (which is added to x)

So for every loop index you get:

i=5 -> x += 1 * 5
i=4 -> x += 7 * 4
i=3 -> x += 8 * 3
i=2 -> x += 9 * 2
i=1 -> x += 5 * 1

So after the loop x contains the value 80 which is returned and assigned to y

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help. That was the explanation I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.