开发者

Simply Pseudocode Question

I'm new to psuedocode, and I'm having trouble puttin开发者_如何学Cg 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?


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. :)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜