Please help with basic recursive problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • freshman
    New Member
    • Sep 2006
    • 2

    #1

    Please help with basic recursive problem

    Hi! I am very new to C programming. I have difficutly in understanding how the recursion work. One of my home work is to write a function using recursion to enter and display a string in reverse and state whether string contain any space - not to use array or string. I spent whole week but cannot list the space counted. Please help. Below is my code: (display string in reverse OK, but cannot count space:

    #include <stdio.h>

    void display(char);
    int count(int);
    int main(void)
    {
    char string;
    printf("Enter a string:\n");
    display(string) ;
    printf("\n\n");
    return 0;
    }
    void display(char ch)
    {
    int space;
    ch = getchar();
    putchar(ch);
    if (ch != '\n')
    display(ch);
    putchar(ch);
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Code:
    void display(char ch)
    {
        int space;
    
        ch = getchar();
        putchar(ch);
        if (ch != '\n')
            display(ch);
        putchar(ch);
    }
    The is no need for ch to be a parameter of the function, you use it as a local variable only (i.e. the value passed in is not used)

    Probably the easiest way to get the number of spaces would be to return it from display

    Code:
    unsigned display(void)
    {
        char ch
        unsigned space;
    
        ch = getchar();
        putchar(ch);/* I think getchar echos the 
                      character anyway so this might be unrequired*/
    
        if (ch != '\n')
        {
            space = display(ch);
        }
        else
        {
            space = 0;
        }
    
        putchar(ch);
    
        if (ch == ' ')
        {
            space++;
        }
    
        return space;
    }

    Comment

    • freshman
      New Member
      • Sep 2006
      • 2

      #3
      Thank you very much for your solution, i appreciated.

      Comment

      Working...