使用递归实现数组求和 | Recursion
#include <iostream>
using namespace std;
void print_array(int* arr, int size) {
//打印数组
cout << "array1={ ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << "}" << endl;
}
int for_sum(int* arr, int size) {
//for循环实现数组求和
int result = 0;
for (int i = 0; i < size; ++i) {
result += arr[i];
}
return result;
}
int recursion_sum(int* arr, int size) {
//递归实现数组求和
if (size == 0) {
return 0;
}
else {
int index = size - 1;
if (index == 0) {
return arr[index];
}
else {
return arr[index] + recursion_sum(arr, size - 1);
}
}
}
int main() {
//数组基本信息
int array1[] = { 1,2,3,4,5,6,7,8,9,0 };
int sizeArray = sizeof(array1) / sizeof(array1[0]);
//打印数组
print_array(array1, sizeArray);
//for循环数组求和
cout << "for循环数组求和:" << for_sum(array1,sizeArray) << endl;
//递归数组求和
cout << "for循环数组求和:" << recursion_sum(array1, sizeArray) << endl;
return 0;
}