Thread: recursivity & iteration

  1. #1
    Learn from the llama Marlon's Avatar
    Join Date
    Jun 2005
    Location
    South africa
    Posts
    25

    Question recursivity & iteration

    Hi, im a novice c++ programmer and im having a bit of diff. understanding recursivity and iteration. Can anyone please give me a clear example. Is it possible to use iteration for a recursive problem? Im trying to figure out a way to solve towers of hanoi using iteration. Any links or help will be appreciated. Thanks

  2. #2
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Have you tried googling 'towers of hanoi'?

    I think the 'cut-the-knot' web site may have the explantion you're looking for. It explains the recursive solution, which is by far the easiest. It then explains the iteration formula and finally it explains the 'non-recursive' solution!

    If this is h/w look into implementing the recursive solution. It's only a few lines of code.

    Recursive just means calling a function from a function. For a more detailed explanation of recursion check out google.


  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Hi, im a novice c++ programmer and im having a bit of diff. understanding recursivity and iteration.
    Hi,

    Well, first things first: it's called "recursion" not recursivitytionabilityness.

    Can anyone please give me a clear example.
    Here's an easy one:
    Code:
    #include <iostream>
    using namespace std;
    
    void recursive1(int n)
    {
    	cout<<n<<endl;
    	
    	if(n > 0) //ending condition
    		recursive1(n-1);
    }
    
    int main ()
    {
       recursive1(9);
    
       return 0;
    }
    Here's one that's a little trickier:
    Code:
    #include <iostream>
    using namespace std;
    
    void recursive2(int n)
    {
    	cout<<n<<endl;
    
    	if(n < 10) //ending condition
    		recursive1(n+1);
    	
    	cout<<n<<endl;
    }
    
    int main ()
    {
       recursive2(5);
    
       return 0;
    }
    Last edited by 7stud; 06-14-2005 at 02:00 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Iteration?
    By Aliaks in forum C++ Programming
    Replies: 2
    Last Post: 06-06-2009, 11:17 PM
  2. iteration revisited
    By robwhit in forum C Programming
    Replies: 3
    Last Post: 09-05-2007, 09:38 AM
  3. MPI - linear pipeline solution for jacobi iteration
    By eclipt in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2006, 05:25 AM
  4. The "continue" statement in JAVA
    By Hexxx in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 02-26-2004, 06:19 PM
  5. Iteration help please
    By incognito in forum C++ Programming
    Replies: 3
    Last Post: 12-09-2001, 07:37 AM