数组进行逆序打印的几种方法

这里暂时提供两种方法,如果以后有想到更好的再添加:

第一种方法是数组的值没有变,仅仅改变输出时的顺序,这个对于仅仅是要求输出逆序的程序非常简单而且有效,且不改变数组的值:

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

程序运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值