Thread: Needed a solution on the following Recursive function

  1. #1
    Registered User Raj 89's Avatar
    Join Date
    Nov 2012
    Chennai, TamilNadu

    Needed a solution on the following Recursive function

    In the below mentioned code i am having a difficulty to understand the logic behind it.

    #include <stdio.h>
    void call(int n )
    if ( n < 0 )
    call(--n) ;
    printf("\n%d",n) ;
    call(--n) ;
    int main(void )
    int a = 3;
    call(3) ;
    return 0 ;
    The output of the code is 0 1 2 0. Why?

  2. #2
    Registered User
    Join Date
    Jun 2012
    Actually your code is pure C not C++.

    Anyway, this particular code should not give us any output. So it's quite a mystery how did you get this "0 1 2 0".
    What compiler are you using?

  3. #3
    Registered User
    Join Date
    Nov 2012
    As mentioned above, the function as written will give no output if the argument is nonnegative. Notice that even if the argument is negative, this would result in an unendless series of recursive calls resulting in undefined (i.e. system-dependent) number of output lines with various integers. Also, why do you set a = 3 in your main function? Finally, if the program does manage to terminate, it will end in the middle of a line without a terminating newline, which is generally not a nice way to end the program's output.

    For recursive functions it helps to identify two cases: the base case and the recursive case. In your call example, you only specified the recursive case "if (n < 0)....". The base case would be a condition to specify where your function will eventually "stop", ending the recursion.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    Quote Originally Posted by Raj 89 View Post
    The output of the code is 0 1 2 0. Why?
    It does not. You have misrepresented the facts.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help needed with Puzzle solution provided in C
    By martin70 in forum C Programming
    Replies: 1
    Last Post: 11-22-2009, 07:36 PM
  2. Recursive solution?
    By Xanz1441 in forum C++ Programming
    Replies: 13
    Last Post: 09-20-2007, 08:14 PM
  3. C Program solution needed...
    By vijay.neo in forum C Programming
    Replies: 6
    Last Post: 10-18-2006, 11:12 PM
  4. Recursive Solution to Any Maze And Stack Overflow Problems
    By PunkyBunny300 in forum C Programming
    Replies: 14
    Last Post: 12-14-2002, 07:00 PM
  5. binary tree solution-- help needed
    By sanju in forum C Programming
    Replies: 3
    Last Post: 10-11-2002, 01:56 AM

Tags for this Thread