recursively annoying...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TMS
    New Member
    • Sep 2006
    • 119

    recursively annoying...

    This recursive function is intended to print all odd numbers starting with the number passed to it. It does that but then, it prints out odd numbers starting with 429496295, and decreasing after that until memory is full or something. The only way I knew it was actually doing what I want it to do plus these other numbers is by hitting pause/break immediately after allowing it to run.
    How am I accessing these crazy numbers?

    Code:
    #include <iostream>
    
    using namespace std;
    
    unsigned int odd(unsigned int n);
    
    int main()
    {
    odd(20);
    
    return 0;	
    }
    unsigned int odd(unsigned int n)
    {
    	if(n==0)
    	{
    	
    		return 1;
    	} //end if
    	if((n%2)==0)
    	{
    		return odd(n-1);
    	} // end if
    	else
    	{
    		cout << n << ", " ;
    		return odd(n-2);
    	} //end else
    }  //end odd()
  • galexyus
    New Member
    • Sep 2006
    • 15

    #2
    The problem is that in your odd function you return odd(n-2) for odd numbers. This makes it impossible for the function to meet the stopping condition n==0, because odd number - 2 would always be odd. And the crazy numbers are caused by underflow. Since you are using unsigned int, if you subtract 2 from 1, you will get the largest odd unsiged int 429496295 and so on.

    This code will do what you need:

    Code:
    #include <iostream>
    
    using namespace std;
    
    unsigned int odd(unsigned int n);
    
    int main()
    {
    odd(20);
    
    return 0;	
    }
    unsigned int odd(unsigned int n)
    {
    	if(n==0)
    	{
    	
    		return 1;
    	} //end if
    	if((n%2)==0)
    	{
    		return odd(n-1);
    	} // end if
    	else
    	{
    		cout << n << ", " ;
    		return odd(n-1);
    	} //end else
    }  //end odd()

    Comment

    Working...