Thread: Help needed in recursion.

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    32

    Help needed in recursion.

    Code:
    #include<stdio.h>
    void print(char *p)
    {
    if(*p)
    print(++p);
    printf("%s\n",p);
    }
    main()
    {
    char *p="ABCD";
    print(p);
    }

    for the above program I'm expecting output as
    Code:
    (null)
    D
    CD
    BCD
    but the ACTUAL output is
    Code:
    (null)
    (null)
    D
    CD
    BCD
    Why printf is printing two NULL?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Recall the effects of ++p.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    2
    It increments to a null and in next call it's a null ( no increment ). Hence, prints both.

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You need to indclude the printf in your if block:
    Code:
    if(*p) {
    
      print(++p);
    
      printf("%s\n",p);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help needed with minesweeper recursion!
    By hellraiser in forum C Programming
    Replies: 11
    Last Post: 04-20-2011, 07:29 AM
  2. Recursion help needed
    By lewiso in forum C Programming
    Replies: 6
    Last Post: 03-02-2008, 12:18 PM
  3. Recursion
    By malooch in forum C Programming
    Replies: 2
    Last Post: 12-18-2006, 12:46 PM
  4. stack and recursion help needed!
    By LouB in forum C++ Programming
    Replies: 3
    Last Post: 07-01-2002, 02:19 PM
  5. Recursion help
    By Magos in forum C++ Programming
    Replies: 0
    Last Post: 03-30-2002, 08:22 AM