Every subprogram consists of a unique name and one or more commands. You can name a subprogram anything although it’s usually best to give a subprogram a descriptive name. So if you create a subprogram to convert yards into meters, you might name your subprogram Yards2Meters or Metric Converter.

 

When this subprogram runs, it calls itself, essentially making a second copy of itself, which then makes a third copy of itself, and so on. A common problem used to demonstrate recursion is calculating a factorial which multiples a number by a gradually decreasing series of numbers. Ultimately, every subprogram that calls itself needs to end. Otherwise, it can get trapped in an endless loop, which hangs or freezes your computer.

 

When a subprogram finally ends, it returns a value to the preceding subprogram, which returns its value to the preceding subprogram, and so on until a value is finally calculated by the first copy of the subprogram that initially ran. Compared to the much smaller and simpler recursive subprogram, this subprogram is harder to understand although it calculates the exact same results. As long as you understand that subprograms are one technique for helping you write larger programs, you can use subprograms as building blocks to create anything you want.

𐌢