zptzdlzc

导航

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;
}

posted on 2022-05-07 20:25  zdlzc  阅读(251)  评论(0编辑  收藏  举报