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

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

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

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

程序运行结果:


全部评论

相关推荐

02-11 12:20
门头沟学院 Java
面试中的青提很胆小:我不信有比我们学校更逆天的,计算机专业就业第一位是我们学校二餐厅的打印店
点赞 评论 收藏
分享
01-24 08:13
已编辑
合肥工业大学 Java
程序员牛肉:没啥问题。标准的流水线简历,但是学历好一点,所以应该是有约面的机会的。 这段时间可以考虑把自己的两个项目彻底的理一理。争取能够讲清楚每一个功能点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务