c++题目详情 编写递归函数,将数组元素逆序,函数的输入参数是数组
作者:野牛程序员:2023-11-20 13:47:36 C++阅读 2768
c++题目详情 编写递归函数,将数组元素逆序,函数的输入参数是数组、起始下标和元素个数。在主函数中输入元素个数和数组元素,调用函数逆序,在主函数中输出结果。设数组类型为整型,元素不超过100个。 输入:元素个数n和n个元素,用空格或换行隔开。 输出:逆序的数组元素,用一个空格隔开,末尾无空格。 【提示】本函数不需返回值。 【注意】必须用递归函数实现,否则没有意义。 样例1输入:5 1 2 3 4 5 样例1输出:5 4 3 2 1
#include <iostream>
using namespace std;
void reverseArray(int arr[], int start, int n) {
if (start < n) {
// Swap the elements at the start and end positions
swap(arr[start], arr[n - 1]);
// Recursively reverse the remaining elements
reverseArray(arr, start + 1, n - 1);
}
}
int main() {
int n;
cin >> n;
int arr[100];
// Input array elements
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
// Reverse the array using the recursive function
reverseArray(arr, 0, n);
// Output the reversed array
for (int i = 0; i < n; ++i) {
cout << arr[i];
if (i < n - 1) {
cout << " ";
}
}
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

