# Help with recursion

Posted by Cornel696
Announcements Last Post
myUnisa availability 21 to 24 March 2019 03/17/2019 02:24PM
SoC Curricula 09/30/2017 01:08PM
Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
School of Computing Short Learning Programmes 11/24/2014 08:37AM
Unisa contact information 07/28/2011 01:28PM
 Help with recursion September 16, 2006 09:44AM IP/Host: ---.saix.net Registered: 12 years ago Posts: 5 Rating: 0
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 IP/Host: ---.ccrl-nece.de Registered: 13 years ago Posts: 3 Rating: 0
Hi,

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.

I hope that I helped you a bit.

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