Welcome! Log In Create A New Profile

Advanced

Help with recursion

Posted by Cornel696 
Announcements Last Post
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
Help with recursion
September 16, 2006 09:44AM
Please help with the following code, I must be getting this all wrong cause using this in recursive doesn’t give me correct results, rewriting this as iterative with a while it works fine.

Question: finding the largest element in an array


///////////////////////////

#include <iostream>


int largest(int first[], int temp, int count, int i)
{

if (count == (i+1))
return temp;

else
{

if (first > temp)
{
temp = first;
i++;
return largest(first,temp,count,i);
}
else
i++;
}

}

using namespace std;

int main() {


int arr[3];

arr[0] = 3;
arr[1] = 7;
arr[2] = 4;
arr[3] = 3;

int temp = 1;
int count = 4; // size of array
int i = 0;


cout <<largest(arr,temp,count,i)<<endl;;


return 0;
}
Re: Help with recursion
September 18, 2006 05:38PM
Hi,

I have tried your code.

It seems that the recursion brakes as soon as you don't get "if (first > temp) ", but "else".

Here is my code:

int largest(int first[], int temp, int count, int i)
{
if (i == count)
return temp;
else {
if (temp < first)
temp = first;
return largest(first,temp,count,i+1);
}
}

Here is the value of "i" and "temp" at the beginning of each function call.

i | temp
0 | 0
1 | 3
2 | 7
3 | 7
4 | 7

Sorry for the bad English, but my home language is German. smile

I hope that I helped you a bit.

Richard
Sorry, only registered users may post in this forum.

Click here to login