I have an assignment and Im trying to do it, but I need to figure out how to do the recursive funtions. I know how to do it with the loop but I want it with the recursive. The funtion is find the smallest value

int findsmallest(int list[], int size)

Printable View

- 01-22-2006AlawamiaHelp Recursive functions
I have an assignment and Im trying to do it, but I need to figure out how to do the recursive funtions. I know how to do it with the loop but I want it with the recursive. The funtion is find the smallest value

int findsmallest(int list[], int size) - 01-22-2006guyonasm
Lets say I want to have an exponential function. Meaning I'll take the first parameter (x) to the second parameter (y) power. Here is what it would look like recursively.

Code:`int power(int x, int y)`

{

if (y == 0)

return 1;

else

return x * power(x, y-1);

}

Better yet, if that doesn't help, can you post the code of your looped method, and I'll help you understand how to translate to recursion. - 01-22-2006Alawamia
Thanks for your reply. I am having a hard time figuring out the recursive. I put the loop because you said can help me to figure out how to do it if i put the loop...so i can learn how to translate it.

Code:`int find_smallest(int list[] )`

{

int i, small =list[0];

i = 1;

while (i< list.length )

{

if ( small > list[i] )

small = list[i];

list+=1;

}

return small;

}

- 01-22-2006guyonasm
That code looks nice :). I'm assuming you're actually using Java :), but for the sake of this being a C++ forum, I'm going to take what you have, and explain it in terms of C++, as your list.length is something I've only seen done while coding in Java :p.

Now that I'm thinking about it, it might be easier just to show you a way.

Code:`int findsmall(int list[], int curr, int size)`

{

if (size-1 == curr)

return list[0];

else

if(list[curr] < list[0])

{

// swap values

int temp = list[curr];

list[curr] = list[0];

list[0] = temp;

}

findsmall(list, curr+1, size);

return list[0];

}

There are many other ways to go about it, and assuming you use Java, the third parameter isn't even needed. - 01-22-2006gamer4life687
Just a word of advice. You should never really need a loop inside of a recursive function because it defeats the point of recursion if the loop is doing the work. On the other hand if you can get a loop to make it work, it shouldnt be to hard to see how to change that into a recursive function.

- 01-23-2006SalemCode:
`int findsmallest(int list[], int size) {`

if ( size == 1 ) return list[0];

else {

int rest = findsmallest( list+1, size-1);

return list[0] < rest ? list[0] : rest;

}

}

- 01-23-2006guyonasmQuote:

Originally Posted by**Salem**