Getting started with algorithms-recursion

Source: Internet
Author: User

thought: Call itself directly or indirectly to perform the next calculation.
A general implementation process: a function or sub-process, either directly or indirectly, by invoking a function or subroutine to perform the calculation.
Requirements: Each time the loop is called, the size of the solution problem must be reduced.    Adjacent two loop calls have to be closely linked, usually the previous invocation result is the input of the last call. There must be an exit, which is the recursive loop end condition.
Note: Recursive invocation of the algorithm is usually less efficient, and too many calls can cause stack overflow.
Example: Finding factorial
#include <stdio.h>int fact (int n); void main () {int i; printf ("Input:"); scanf ("%d", &i); printf ("The factorial result of%d is:%d", i,fact (i)); Getch ();} int fact (int n) {if (n<=1)  return 1; Else  return fact (n-1) *n;}
Analysis: Recursive algorithm thought is not difficult, simply said: is repeated call itself to solve the problem. But the timing of choosing recursion is very important, and some complex problems can be solved simply by recursion. This requires careful analysis. Run Process: When the program runs toprintf ("The factorial result of%d:%d", i,fact (i)) begins to invoke the function fact (i). In the function fact (), n=i; determine whether n is less than or equal to 1 (this is important, is the condition of the end of recursion), is less than the return 1, otherwise returns the fact (n-1) *n, that is, the function of the call again the fact (), and the function of the parameters of 1, This satisfies the recursive principle that each invocation of the problem scale must be reduced. Once again the call is then judged, then called, and then judged, until n is less than or equal to 1. At this point, the return value of the function becomes larger and greater until the result is reached by recursive calls of several times.


Getting started with algorithms-recursion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.