Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

What is recursion in C used for?

From what I understand, It's a functions within itself. However I don't understand what the purpose of this is and why it's used. Could you explain why and when this should be used (other than to find out the factorial of a number)? What are the different things I need to know about recursion? Thanks!

2 Answers

Relevance
  • 8 years ago
    Favorite Answer

    Recursion is a function *calling* itself. One of the classic examples is traversing a directory to get all files in all subfolders. Here's an example in C#

    public void GetAllFiles(directoryPath)

    {

    foreach (string file in Directory.GetFiles(directoryPath)

    {

    yield return file;

    }

    foreach (string subfolder in Directory.GetDirectories(directoryPath))

    {

    // This is where the recursion happens. We can't know

    // how deep the directory structure is, so one option is to

    // simply call this function recursively, which will keep

    // digging down the directory tree until there are no more

    // subfolders and return all files found.

    foreach (string file in GetAllFiles(subfolder))

    {

    yield return file;

    }

    }

    }

  • 7 years ago

    listen i will explain it the simple way. Suppose some company make a cab. There is no compulsion that jack will only ride the taxi. Any one can hire that cab by calling in there office. Like wise a recursive function is like a cab. You can call it any number of times.. unless a condition is fulfilled,..say our gas tank is empty..we cannot drive the cab anymore ... hope it helps. There are far many application of recursion rather than finding Factorials... it cannot be more that simple than this.

Still have questions? Get your answers by asking now.