In the calculation of 1+2+3+4+5, two forms of recursive method are used to practice the main view of recursive law, to train recursion and to form the "instinct" of recursion.
The first , from the back to the Add.
int sum (int a[],int n) { return n==0? 0: Sum (a,n-1) +a[n-1];}
The second , from both sides of the Add, example: (1+5) + (2+4) +3, this needs to be determined, if the number of arrays is even, then the left +1== to the right, if it is odd, then left +2== to the right, you need to return these three numbers:
int sum (int a[],int l, R) { if (L+2 ==r) /* */ return a[l]+a[l+< Span style= "color: #800080;" >1 ]+a[r]; if (L+1 = = r) A[R]; return sum (a,l+1 , R-1 ) +a[l]+a[r];}
/*------Full Code @ Reflection Snow-------*/#include<iostream>using namespacestd;intSumintA[],intLintR) { if(L +2==R)/*one element in the interval*/ returna[l]+a[l+1]+A[r]; if(L +1==R)returna[l]+A[r]; returnSUM (a,l+1, R-1) +a[l]+a[r];}intMain () {inta[]={1,2,3,4,5}; cout<<sum (A,0,sizeof(a)/sizeof(int)-1); return 0;}
2. Simple summation [recursive method]