What is the difference between iteration and recursion?

后端 未结 8 786
太阳男子
太阳男子 2021-01-30 11:52

What is the difference between iteration and recursion and why/when is one better:

while (true) {
    // Iterating
}

相关标签:
8条回答
  • 2021-01-30 12:21

    Recursive functions work through the process of calling themselves until a condition is met whereas iteration uses a looping control structure (for example while, do while, for) in order to repeat a section of code until a certain condition is met.

    Recursive example:

    int rec_func(int u, int k) {
      if (k == 0)
        return u;
      return rec_func(u * k, k - 1);
    }
    

    Iteration example:

    int ite_func(int u, int k) {
      while (k != 0) {
        u = u * k;
        k = k - 1;
      }
      return u;
    } 
    

    The only real difference IMO between them is compilation differences.

    0 讨论(0)
  • 2021-01-30 12:23

    Recursion and iteration are different ways to think about a solution. It would be dificult to explain in depth the difference in full scope. In your sample code, you aleady showed the difference. Recursive function is the one that calls itself, while iterative is the one that loops through some block of code. Here are some articles to help you understand them better: Recursion wiki

    Iteration wiki

    CodeProject SO #1

    SO #2

    0 讨论(0)
提交回复
热议问题