reverse a string with recursive function it is to be terminated by space not by enter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anand vishwakar
    New Member
    • May 2011
    • 6

    reverse a string with recursive function it is to be terminated by space not by enter

    Hi all,

    I prepared a program in c language to reverse a string using recursive function

    In my program I terminated the string using new line character '\n'

    But I want to change my program in the way that if a white space is pressed after typing a word then space bar ' ' should be used to terminate the string and string should be printed in reverse order

    but when I used statement

    Code:
    if((ch=getchar())!=' ')
    rev();
    then string is not being terminated after executing the program

    here is the coding I used to apply my logic

    Code:
    void rev(void)
    {
    char ch;
    
    if((ch=getchar())!='\n')
    {
    rev();
    printf("%c",ch);
    }
    }
    please guide me about the solution to this problem

    Thank you
    Last edited by Meetee; May 3 '11, 05:08 AM. Reason: please apply code tags
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Well, you don't really have a string here. What you have is one character at each level of recursion.

    To reverse a string, the easiest thing to do is swap the first and last characters of the string.

    So in thiscase you call rev() with the address of the first and last character. When rev() calls rev() is does no by passing the addresses of the next character from the left and the previous character on the right.

    rev() returns when the ttwo addressws ae equal.

    And your string is reversed.
    Now just display it in main().

    You don't actually need delimiters. All you need is the address of the first and last character in the range of characters thest need reversing.

    Comment

    • anand vishwakar
      New Member
      • May 2011
      • 6

      #3
      thank you for your valuable help
      and I have also found a mistake in my logic to reverse a resies of entered characters actually I should have used getche() function in place of getch() then my logic is working . Thank You

      Comment

      Working...