Learning recursion after understanding loops but not seeing when recursion is actually useful

I understand loops, and every beginner recursion example seems to replace an easy loop with a function that calls itself. Factorials don't convince me. I can follow the base case mechanically, but I don't see why I'd choose recursion in real code. Could someone explain it through a naturally nested problem, like walking a directory tree or processing a hierarchy, and show where the recursive structure genuinely makes things simpler?

  • programming-help
  • recursion
  • understanding
  • loops
45

5 replies · Sort: Best

Best

1 reply from the original poster, shown with the conversation around them.

  1. xiao.si
    4 points

    4 replies

    Recursion helps when the problem is naturally made of smaller copies of itself. A directory tree is the classic example: a folder contains f...

    44 replies

    Recursion helps when the problem is naturally made of smaller copies of itself. A directory tree is the classic example: a folder contains files and other folders, and each subfolder needs the same logic as the top one.

    4
    1. EG
      eva_georg
      1 point

      That’s the part that clicked for me too. The code mirrors the shape of the data, so you spend less time manually managing levels.

      1
    2. CS
      charles_5
      4 points

      A simple loop can visit every item in a flat list, but a tree has depth you don’t know in advance. Recursion lets the function handle one node and hand the smaller version of the same job to itself.

      4

        I used to think recursion was just a fancier loop until I saw a menu system with nested submenus. Then it made sense that the same function...