Song that Never Ends

To be fair, that song does eventually end, if only because YouTube has a limit on length. But it certainly sounds like it repeats forever, as might happen if a function calls itself. Indeed, consider an implementation of that song in Python, below.

def main():
    sing()


def sing():
    print("This is the song that doesn't end.")
    print("Yes, it goes on and on my friend.")
    print("Some people started singing it not knowing what it was,")
    print("And they'll continue singing it forever just because...")
    sing()


if __name__ == "__main__":
    main()

Notice how sing calls itself in its last line, thereby ensuring the song never, in fact, ends. Now, a function that calls itself is said to be "recursive," and this technique, otherwise known as "recursion," is quite helpful when implementing some algorithms. But bad things can happen if a function calls itself too many times in succession!

Answer the below in song.md, song.c, and song.py:

Questions

  1. (1 point.) Precisely what error do you eventually see if you execute the program above, as by first copying and pasting it into a file in CS50 IDE?

  2. (2 points.) Reimplement, in song.c, this same program in C in such a way that the C version is also recursive. Your program must compile not with make but with

    clang -o song song.c

    instead, without any warnings or errors.

  3. (1 point.) Precisely what error do you eventually see if you execute your compiled C version?

  4. (2 points.) Why does the C version eventually err?

  5. (2 points.) Reimplement, in song.py, this same program in Python in such a way that it is no longer recursive and will actually execute forever without that eventual error.

  6. (2 points.) Recall from Week 0 how David ultimately searched for a phone number in logarithmic time. In what sense was that algorithm recursive?

Debrief

  1. Which resources, if any, did you find helpful in answering this problem’s questions?

  2. About how long, in minutes, did you spend on this problem’s questions?