Thread: recursion help

  1. #1
    Unregistered
    Guest

    recursion help

    Hi, I am trying to learn some recursion and I am having trouble following this simple program:

    #include <iostream>
    #include <stdlib.h>
    using namespace std;

    void fun(int x);

    int main(void)
    {
    fun(3);

    }

    void fun(int x)
    {
    if (x != 1) {
    fun(x - 1); // fun calls fun
    cout << x << endl;
    }
    }

    The output is:

    2
    3

    This is my understanding:

    x=3: so is 3 !=1 true so fun(3-1) or fun(2)

    so is 2 !=1 true so fun(2-1) or fun(1)

    so is 1 !=1 false

    cout x (doesn't x=1 ??)

    and why are two numbers printed?

    I'm sure this is simple for many of you, but I am simple, and if you could break it down for me I would be grateful.

  2. #2
    Evil Member
    Join Date
    Jan 2002
    Posts
    638
    Your problem has nothing to do with recursion. The cout is part of the if block, and is not executed if x != 1.

  3. #3
    Registered User biosx's Avatar
    Join Date
    Aug 2001
    Posts
    230
    Code:
    #include <iostream> 
    #include <stdlib.h> 
    using namespace std; 
    
    void fun(int x); 
    
    int main(void) 
    { 
       fun(3); 
    } 
    
    void fun(int x) 
    { 
       if (x != 1) 
          fun(x - 1); // fun calls fun 
    
       cout << x << endl; 
    }
    That should work the way you want.

  4. #4
    Unregistered
    Guest
    Thanks for the replies.

    But what I would like to understand is why the output is:

    2
    3

    When I try to trace it on paper I can not get that output. I know it is right (obviously) but can someone explain it to me.

    Can you take me step by step through the logic of the program.

    Thanks for your time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. convert Recursion to linear can it be done
    By umen242 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2008, 02:58 AM
  3. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  4. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  5. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 09:24 AM