C++之递归遍历数组
倒序输出
源码
void print_arr_desc(int arr[], unsigned int len)
{
if (len)
{
std::cout << "a[" << len - 1 << "]=" << arr[len - 1] << "\n";
print_arr_desc(arr, len - 1);
}
// 确定结束条件
else
return;
}
测试结果
int arr[] = { 1, 2, 3, 4, 5 };
print_arr_desc(arr, 5);
顺序输出
代码
void print_arr_asc(int arr[], unsigned int len)
{
if (len)
{
print_arr_asc(arr, len - 1);
std::cout << "a[" << len - 1 << "]=" << arr[len - 1] << "\n";
}
else
;
}
测试
int arr[] = { 1, 2, 3, 4, 5 };
print_arr_asc(arr, 5);
测试输出