Jump to content

  • Log In with Google      Sign In   
  • Create Account

Help with Recursion in C++


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
18 replies to this topic

#1 Bladelock   Members   -  Reputation: 123

Like
0Likes
Like

Posted 15 March 2011 - 06:46 AM

Well I'm currently in the topic of function recursion, so i tried this function which supposedly displays 1 to 10 using a recursive function named recurse().

It runs, but nothing shows in the console window upon execution.

Here is the code



#include <iostream>
using namespace std;

int x;

void recurse();

int main()
{
	
	x = 0;
	recurse();
	
	char end;        // This is my ending sequence to prevent program from closing immediately
	cin >> end;
	cin.ignore(end);
	return 0;	
}

void recurse()
{
	
	x = x + 1;
	if(x = 11){	
		return;}
	else{	
	cout << x << "\n";
	recurse();
	}
	
}




That's my code basically. I would appreciate to know what went wrong with my code. Thank you!

Sponsor:

#2 Cupu   Members   -  Reputation: 102

Like
1Likes
Like

Posted 15 March 2011 - 06:54 AM

Hi,

You have a typo in your test to stop recursion
if(x = 11)

should be:

if(x == 11)

The first way will assign the value 11 to x and then evaluate x's value (which is 11, that is something different than 0 and evaluates to true; therefore that code path will always be taken.

Cheers!

--
Edit: typos

#3 rip-off   Moderators   -  Reputation: 8217

Like
1Likes
Like

Posted 15 March 2011 - 06:55 AM

You have an assignment in your conditional. The line if(x = 11) sets x to 11, and then tests if 11 is non-zero. It is, so the function always returns immediately.

#4 ericbeg   Members   -  Reputation: 108

Like
1Likes
Like

Posted 15 March 2011 - 07:41 AM

You might avoid the global declaration of the x variable. That would make you recursion function self contained, or a bit more readable.

I would re-write such function as this:

int recurse( int x )
{
    	cout << x << "\n";

    	if( x < 10 )
	   	x = recurse( x + 1 );

        return x;
}


#5 kaktusas2598   Members   -  Reputation: 846

Like
1Likes
Like

Posted 15 March 2011 - 07:49 AM

I agree to that ericbeg said - Avoid globasllvariables as much as you can, pass local variable x to your function instead
Behind every great fortune lies a great crime.
Honore de Balzac

#6 NightCreature83   Crossbones+   -  Reputation: 2825

Like
1Likes
Like

Posted 15 March 2011 - 03:15 PM

You might avoid the global declaration of the x variable. That would make you recursion function self contained, or a bit more readable.

I would re-write such function as this:

int recurse( int x )
{
    	cout << x << "\n";

    	if( x < 10 )
   		x = recurse( x + 1 );

        return x;
}





void recurse(int x)
{
        cout << x << "\n";
    	if( x < 10 )
            recurse( x + 1 );
}


Would do the same thing and avoids an unnecessary return value, this is better unless you actually need the value outside of the recurse function.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#7 D.Chhetri   Members   -  Reputation: 181

Like
0Likes
Like

Posted 15 March 2011 - 03:35 PM

This isn't a better solution, but another way to look at it :
void print1To10(){
 _print(1,10);
}


void _print(const int begin, const int end){
  if(begin <= end) cout << begin;
  else _print(begin+1,end);
}

Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github

#8 rip-off   Moderators   -  Reputation: 8217

Like
0Likes
Like

Posted 15 March 2011 - 04:16 PM

It is traditional not to post direct answers to homework questions.

#9 NightCreature83   Crossbones+   -  Reputation: 2825

Like
2Likes
Like

Posted 15 March 2011 - 05:21 PM

It is traditional not to post direct answers to homework questions.


To be fair he figured the recursion out by himself, just a minor syntax error which is easy to mis when you are staring at it for a few hours. The rest are just improvements on what he had, you need to read quite a bit of code before you can actually write code, imo.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#10 Bladelock   Members   -  Reputation: 123

Like
0Likes
Like

Posted 17 March 2011 - 02:08 AM

Thanks! You guys helped a lot!

#11 way2lazy2care   Members   -  Reputation: 782

Like
0Likes
Like

Posted 17 March 2011 - 11:58 AM

This isn't a better solution, but another way to look at it :

void print1To10(){
 _print(1,10);
}


void _print(const int begin, const int end){
  if(begin <= end) cout << begin;
  else _print(begin+1,end);
}

this will print just 1.

I think you mean :
void print1To10(){
 _print(1,10);
}


void _print(const int begin, const int end){
  if(begin <= end) _print(begin+1,end);
  cout << begin;
}


#12 belfegor   Crossbones+   -  Reputation: 2613

Like
1Likes
Like

Posted 17 March 2011 - 01:48 PM

To avoid future mistakes put literal constants on left side so that you can caught this potentially nasty bug at compile time:
...
if( 11 = x )//error
if(11 == x) //fine and same as if(x == 11)


#13 Álvaro   Crossbones+   -  Reputation: 13311

Like
0Likes
Like

Posted 17 March 2011 - 02:11 PM

To avoid future mistakes put literal constants on left side so that you can caught this potentially nasty bug at compile time:

...
if( 11 = x )//error
if(11 == x) //fine and same as if(x == 11)


I've seen this kind of thing before, but I don't know if it really helps anything: If you can remember to put the number first, you can also remember to write "==" instead of "=".

#14 sjaakiejj   Members   -  Reputation: 130

Like
3Likes
Like

Posted 17 March 2011 - 02:16 PM


To avoid future mistakes put literal constants on left side so that you can caught this potentially nasty bug at compile time:

...
if( 11 = x )//error
if(11 == x) //fine and same as if(x == 11)


I've seen this kind of thing before, but I don't know if it really helps anything: If you can remember to put the number first, you can also remember to write "==" instead of "=".


It does help, as doing that every time makes it a habbit, whilst missing out an "=" can often be due to a typo, and lead to an incredible headache when debugging.

#15 Álvaro   Crossbones+   -  Reputation: 13311

Like
0Likes
Like

Posted 17 March 2011 - 02:20 PM

It does help, as doing that every time makes it a habbit, whilst missing out an "=" can often be due to a typo, and lead to an incredible headache when debugging.


Well, I made a habit of writing "==". I think it's been about 18 years since the last time I made that mistake.

#16 belfegor   Crossbones+   -  Reputation: 2613

Like
0Likes
Like

Posted 17 March 2011 - 02:41 PM

I think it's been about 18 years since the last time I made that mistake

Good for you.

#17 way2lazy2care   Members   -  Reputation: 782

Like
0Likes
Like

Posted 17 March 2011 - 05:32 PM


It does help, as doing that every time makes it a habbit, whilst missing out an "=" can often be due to a typo, and lead to an incredible headache when debugging.


Well, I made a habit of writing "==". I think it's been about 18 years since the last time I made that mistake.


if I'm writing a long set of conditionals it's pretty easy to slip and miss an =, or if some crumbs get in your keyboard. It's an easy thing to miss, and it's a pain to debug because when you look at it it's really easy to see '=' as '==' even though they are completely different.

Doesn't happen often, but when it does it's pretty annoying.

#18 lmelior   Members   -  Reputation: 322

Like
0Likes
Like

Posted 17 March 2011 - 05:39 PM

Also, it's especially good practice to put the constant first if you will be sharing code. Consider the time back in 2003 when somebody inserted malicious code into a CVS clone of the main BitKeeper repository for the Linux kernel. In the wait4 function they added:

if ((options == (__WCLONE|__WALL)) && (current->uid = 0))

A handy little backdoor to gain root privileges for any program you choose simply by calling wait4 and compiling with the right options. Maybe you and everybody with push access to your repository is sharp eyed enough to catch these every time, but requiring the constant on the left means you don't have to be.

#19 NightCreature83   Crossbones+   -  Reputation: 2825

Like
0Likes
Like

Posted 18 March 2011 - 05:08 AM

Also, it's especially good practice to put the constant first if you will be sharing code. Consider the time back in 2003 when somebody inserted malicious code into a CVS clone of the main BitKeeper repository for the Linux kernel. In the wait4 function they added:

if ((options == (__WCLONE|__WALL)) && (current->uid = 0))

A handy little backdoor to gain root privileges for any program you choose simply by calling wait4 and compiling with the right options. Maybe you and everybody with push access to your repository is sharp eyed enough to catch these every time, but requiring the constant on the left means you don't have to be.


I don't think it should be required in any project, it should however be a guideline when writing code, so more of a preferred style than be strictly enforced. This makes less people balk at restrictive coding style rules, which leads to happier developers.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS