数组进行逆序打印的几种方法
这里暂时提供两种方法,如果以后有想到更好的再添加:
第一种方法是数组的值没有变,仅仅改变输出时的顺序,这个对于仅仅是要求输出逆序的程序非常简单而且有效,且不改变数组的值:
#include <iostream>
using namespace std;
int main()
{
cout<<"please input five numbers:"<<endl;
const int n=5;
int a[n],i;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"the arry that you have inputed is:"<<endl;
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl<<"now the arry is:"<<endl;
for(i=4;i>0;i--)
{
cout<<a[i]<<" ";
}
cout<<a[0];
cout<<endl;
return 0;
}
程序运行结果:
而第二种写法则是将数组内部进行调换,然后进行顺序输出:
#include <iostream>
using namespace std;
int main()
{
const int n = 5;
int a[n] = { 0 };
int i, temp = 0;
cout << "please input five numbers:" << endl;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
cout << "the array that you have inouted is:" << endl;
for (i = 0; i <n; i++)
{
cout << a[i] << " ";
}
cout << endl;
for (i = 0; i<n / 2; i++)
{
temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
cout << "the sorted array is:" << endl;
for (i = 0; i <n; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
程序运行结果: