bitmoe
bitmoe

Reputation: 391

Simply Pseudocode Question

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:

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

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?

Upvotes: 1

Views: 519

Answers (3)

arscariosus
arscariosus

Reputation: 1356

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.

Upvotes: 0

dan04
dan04

Reputation: 90995

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.

Upvotes: 1

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

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

Upvotes: 2

Related Questions