Thread: Function Recursion

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    16

    Function Recursion

    Code:
    #include <iostream.h>
    
    void recurse(int i)
    {
    	if (i == 1)
    	{
    		i = 0;
    		recurse(i);
    	}
    	//Statements
    }
    
    int main()
    {
    	recurse(1);
    
    	return 0;
    }
    In the preceeding program why do "//Statements" run twice? How can I make it run only once?

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Replace <iostream.h> with:
    Code:
    #include <iostream>
    using namespace std;
    Now, to your question, simply follow the calls:
    > main
    -> recurse (i = 1) [since i == 1, call recurse(i = 0)
    --> recurse (i = 0) [i != 1, so don't call recurse again]
    --> statements [from recurse(0), since recurse was not called again]
    -> statements [from recurse(1), after the statements in the if-block have finished]
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    16
    Quote Originally Posted by Zach L.
    Replace <iostream.h> with:
    Code:
    #include <iostream>
    using namespace std;
    Now, to your question, simply follow the calls:
    > main
    -> recurse (i = 1) [since i == 1, call recurse(i = 0)
    --> recurse (i = 0) [i != 1, so don't call recurse again]
    --> statements [from recurse(0), since recurse was not called again]
    -> statements [from recurse(1), after the statements in the if-block have finished]
    Thanks for that. Here's another newbie question: What's the difference between <iostream> and <iostream.h>?

  4. #4

  5. #5

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  4. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM