Recursion and Iteration

前端 未结 7 567
故里飘歌
故里飘歌 2020-12-18 08:43

What is the difference? Are these the same? If not, can someone please give me an example?

MW: Iteration - 1 : the action or a process of iterating or repeating: as

7条回答
  •  情深已故
    2020-12-18 09:06

    Here's a Lisp function for finding the length of a list. It is recursive:

    (defun recursive-list-length (L)
      "A recursive implementation of list-length."
      (if (null L)
          0
        (1+ (recursive-list-length (rest L)))))
    

    It reads "the length of a list is either 0 if that list is empty, or 1 plus the length of the sub-list starting with the second element).

    And this is an implementation of strlen - the C function finding the length of a nul-terminated char* string. It is iterative:

    size_t strlen(const char *s)
    {
        size_t n;
    
        n = 0;
        while (*s++)
            n++;
        return(n);
    }
    

    You goal is to repeat some operation. Using iteration, you employ an explicit loop (like the while loop in the strlen code). Using recursion, your function calls itself with (usually) a smaller argument, and so on until a boundary condition (null L in the code above) is met. This also repeats the operation, but without an explicit loop.

提交回复
热议问题