c++正向、反向输出数组中的元素值(递归实现)
正向输出:
#include<iostream>
using namespace std;
int sum(int a[],int n)
{
if (n == 0)
return 0;
else
{
sum(a, n - 1);
int b=0;
b = a[n - 1];
cout << b << " ";
}
}
int main()
{
int m;
cin >> m;
int *a = new int[m];
for (int j = 0;j < m;j++)
{
cin >> a[j];
}
sum(a, m);
system("pause");
return 0;
}
反向输出:
#include<iostream>
using namespace std;
int sum(int a[],int n)
{
if (n == 0)
return 0;
else
{
int b=0;
b = a[n - 1];
cout << b << " ";
sum(a, n - 1);
}
}
int main()
{
int m;
cin >> m;
int *a = new int[m];
for (int j = 0;j < m;j++)
{
cin >> a[j];
}
sum(a, m);
system("pause");
return 0;
}