1

I am trying to create a recursive function with the output:

Once upon a time, there was a child who couldnt sleep, so the child's mother told her a story about a mouse who couldnt sleep, so the mouse's mother told her a story about a turtle who couldnt sleep, so the turtle's mother told her a story about a frog who couldnt sleep, so the frog's mother told her a story about a bear who went to sleep.

Then the frog went to sleep. Then the turtle went to sleep. Then the mouse went to sleep. Then the child went to sleep.

I have the first paragraph done but when I tried to re loop back around and print out the next paragraph it turns into an infinite loop. Do I need another recursive function to complete this? Any help would be appreciated.

#include <stdio.h>
#include <stdlib.h>

void story(char **string1, int n)
{
    if ( n > 0 )
    {
        printf("a %s who couldn't sleep,\n", *(string1 + n));
        printf("so the %s's mother told her a story about\n", *(string1 + n));
        story(string1, n - 1);
    }
    else
    {
        printf("a %s who went to sleep.", *string1);
        if ( n < 4)
        {
            story(string1, n + 1);
            printf("Then the %s went to sleep.", *(string1 + n));
        }
    }
}

int main()
{
    char* animals[] = {"bear", "frog", "turtle", "mouse", "child"};
    int start = 4;

    printf("Once upon a time, there was ");
    story(animals, start);

    printf("%s", *animals);
    return 0;
}

1 Answer 1

1

The problem is that your recursion goes down (n - 1) when n > 0, and when it hits 0 it calls itself again with 1 (n + 1) which again would call with 0 (n - 1) indefinitely.

What you probably wanted to do is:

void story(char **string1, int n)
{
    if ( n > 0 )
    {
        printf("a %s who couldn't sleep,\n", *(string1 + n));
        printf("so the %s's mother told her a story about\n", *(string1 + n));
        story(string1, n - 1);
        printf("Then the %s went to sleep.", *(string1 + n));
    }
    else
    {
        printf("a %s who went to sleep.", *string1);
    }
}

So each iteration before the last (n == 0) prints it's part and calls the recursion to fill the "middle" till it's time to "go to sleep". The ending rule, n == 0, only prints "... who went to sleep".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I wasn't exactly sure on how to print out the last part but exactly what you did makes perfect sense!
Is the else or where n= 0 considered the base case? @Amit
Yeah, you could say that. I call it the ending rule in this scenario since this type of recursion doesn't use the result of inner iterations to calculate current result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.