• 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.

18 replies to this topic

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!

### #2Cupu  Members

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

### #3rip-off  Moderators

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.

### #4ericbeg  Members

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;
}

### #5kaktusas2598  Members

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

Deltron Zero and Automator.

### #6NightCreature83  Members

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, theHunter, theHunter: Primal, Mad Max

### #7D.Chhetri  Members

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);
}


Visit my site
Visit my github

### #8rip-off  Moderators

Posted 15 March 2011 - 04:16 PM

### #9NightCreature83  Members

Posted 15 March 2011 - 05:21 PM

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, theHunter, theHunter: Primal, Mad Max

Posted 17 March 2011 - 02:08 AM

Thanks! You guys helped a lot!

### #11way2lazy2care  Members

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;
}


### #12belfegor  Members

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  Members

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 "=".

### #14sjaakiejj  Members

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  Members

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.

### #16belfegor  Members

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.

### #17way2lazy2care  Members

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.

### #18lmelior  Members

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.

### #19NightCreature83  Members

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, theHunter, theHunter: Primal, 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.