LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-27-2006, 12:07 AM   #1
harrylee2003
LQ Newbie
 
Registered: Nov 2004
Posts: 23

Rep: Reputation: 15
Recursion to find Max


int findMax(int a[], int n)
{
int max = 0;
if(n == 1)
{
if(a[0]> max)
{
return a[0];
}
}
else
{
if(a[n-1] > max)
{
max = a[n-1];
findMax(a,n-1);
}
}

}

No matter what i enter, it will return 0...
what wrong with it??
 
Old 07-27-2006, 12:16 AM   #2
crazyjimbo
Member
 
Registered: Mar 2006
Location: Edinburgh
Distribution: Debian Etch, Gentoo
Posts: 90

Rep: Reputation: 16
On first glance, in your second if statement, you will need to return the value of findMax. Also every time you call findMax, max is set to zero. Declare max as 'static int' to preserve its value across functions. I don't know if you are doing this as an exercise in recursion but it seems that a simple loop would be easier to implement and use less resources.

PS please post all code within [code ] [/code ] tags (without spaces) as this preserves the formatting and makes it easier to read.

Last edited by crazyjimbo; 07-27-2006 at 12:18 AM.
 
Old 07-27-2006, 10:30 AM   #3
harrylee2003
LQ Newbie
 
Registered: Nov 2004
Posts: 23

Original Poster
Rep: Reputation: 15
Thx
i'm learning c++ now and this just a exercise for me
by thx anyaway
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
chmod recursion -- files only Risc91 AIX 16 09-28-2016 11:15 AM
Recursion in C hubabuba Programming 12 10-03-2005 07:46 AM
Perl, recursion ivanatora Programming 11 03-14-2005 01:49 PM
tar: '--no-recursion' option doesn't prevent recursion Earl Parker II Slackware 12 08-17-2004 02:49 AM
help with recursion function debdas Programming 4 05-14-2003 03:03 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:09 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration