C # recursion

Source: Internet
Author: User

First, the concept of conception:

The function body calls the function itself until a condition is met and no further calls are continued.

Second, should meet the conditions factor:

(1) There is a process of repeated execution (call itself);

(2) There are conditions for jumping out of the process of repeated execution (function exit)

Third, example example

Calculation of factorial n! = N (n-1) * (n-2) * (n-3)*... * ( n>0 )

Iv. Precautions Notice:

1. There must be a loop-over condition in the recursion.

2, each call of the recursive function needs the stack to store, if the number of times too many words easily cause stack overflow.

Examples//A flock of sheep rushed to the villages to sell, each lost a village before the total number of 1/2 1, after 7 villages left two, asked how many sheep originally driven outclasshanshu{ Public intDgqiuyang (intCun//To seek the sheep by hand        {            intsum =0; if(Cun = =7)            {                return 2; } Sum=2* (Dgqiuyang (Cun +1) +1);//The initial cun=1 does not satisfy the marginal condition, always calls Cun+1,//until meet cun==7, get value Dgqiuyang (7) = ' 2 ' sheep//number of sheep in the 6th village Dgqiuyang (6) =2* (Dgqiuyang (7) +1) =2* (2+1) = 6 Sheep//number of sheep in the 5th village Dgqiuyang (5) =2* (Dgqiuyang (6) +1) =2* (6+1) = 14 Sheep//repeat the above steps until the first village is counted, and the output sum is the result.             returnsum; }        Static voidMain (string[] args) {Hanshu HB=NewHanshu (); Doublex = Hb.dgqiuyang (1); Console.Write ("To seek the sheep by hand"+x);           Console.ReadLine (); }}

C # 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.