int arraySum (int [] a, int n)
{
int sum = 0;
n = a.size();
for (int i = 1; i < n; i++)
sum += a[i];
return sum;
}
我想将此代码从迭代转换为递归。
答案 0 :(得分:1)
C#版本:
int arraySum ( int [] a, int sum = 0, int i = 0 ) /*i = 0, technically means this code is logically different from yours, however it will count every element and is just a default :)*/
{
if( i < a.Length )
return arraySum( a, sum + a[i], ++i );
return sum;
}
答案 1 :(得分:0)
你需要:
1-递归定义,如:sum(n) = n + sum(n-1)
2-您需要指定停止的位置,以便递归不会永远持续。
例如:if (n == 0) return 0;
基于此,您可以使用任何语言进行编码。
C ++示例:
int arraySum (int a[], int n)
{
if(n==1)
return a[n-1];
else
return a[n-1] + arraySum (a, n-1);
}