Reputation: 409
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;
}
Upvotes: 1
Views: 1117
Reputation: 46361
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".
Upvotes: 1