views:

91

answers:

3

I'm new to psuedocode, and I'm having trouble putting all the pieces together:

Here is the definition of a function named foo whose inputs are two integers and an array of integers a[1] ... a[n].

1 Foo(k,m, a[1],...,a[n]) 
2   if (k < 1 or m > n or k > m) return 0 
3   else return a[k] + Foo(k+1,m,a[1],...,a[n])

Suppose that the input integers are k=2 and m=5 and the input array contains [5, 6, 2, 3, 4, 8, 2]. What value does Foo return? Using summation notation, give a general formula for what Foo computes.

This one is making my head hurt. Here's what I did so far:

Line 2 has three conditional statements:

  • If k<1 // if 2<1..this is false
  • If m>n // if 5 is greater than the amount of values in the array, which is 7, so this is false
  • If k>m // if 2>5, this is false

So this function will display line 3. Line 3 says:

  • return a[k] which is a[2] which is the second value of the array, which is 6. So take 6 and add it to (2+1, 5, a[1].....,a[n])

Is what I have done correct up there? If so, how would I know what a[n] is? Am I supposed to be finding that? What would be the final result of all this?

+2  A: 

Simple answer: that function returns the sum of all the numbers a[k], a[k+1], ... a[m].

What you're doing is correct so far. The "n" is just a placeholder meaning the last element of the array. So if your input array is {5,6,2,3,4,8,2}, n = 7 (cause your have seven elements), and a[n] = 2.

But why it returns the sum of all numbers a[k], a[k+1], ... a[m], you should find out for yourself. Just continue with your analysis. :)

Richard Neil Ilagan
+1  A: 

So take 6 and add it to (2+1, 5, a[1].....,a[n])

Take 6 and add it to Foo(2+1, 5, a[1].....,a[n]). It's a recursive function. You have to evaluate the function again with k=3 and m=5.

dan04
Recursive? So its not as simple as taking line 3 and displaying the result? So 6+(2+1, 5, a[1].....,a[n])would be 6+(3, 5, 5,6,2,3,4,8,2)which is 6+(38) which is 44? Is this the correct answer?
fprime
Foo(2, 5, a) = 6 + Foo(3, 5, a). Foo(3, 5, a) = 2 + Foo(4, 5, a). Foo(4, 5, a) = 3 + Foo(5, 5, a). Foo(5, 5, a) = 4 + Foo(6, 5, a). Foo(6, 5, a) = 0.
dan04
What the?? What happened there? How did you do this?
fprime
**recursion** *n.* If you don't understand recursion, see **recursion**.
dan04
I know what recursion is its when a function calls itself. Ok I think I see what you did there, but what exactly is 'a'? Is that just the sum of all the values in the array?
fprime
a is the array itself. I didn't feel like typing `a[1]...a[n]`.
dan04
A: 

I think you are confused because your pseudocode looks like real code to me. I may be wrong, but we are taught to write pseudocode differently, using plain English phrases.

arscariosus