Function Recursion

This is a discussion on Function Recursion within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream.h> void recurse(int i) { if (i == 1) { i = 0; recurse(i); } //Statements } int ...

  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
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465

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

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, 09:18 PM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 04: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21