问题描述
编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中。当用户输入0时,表示输入结束。然后程序将把这个数组中的值按逆序重新存放,并打印出来。要求:(1)只能定义一个数组;(2)在交换两个数组元素的值时,必须使用单独定义的一个函数swap。例如:假设用户输入了一组数据:7 19 -5 6 2 0,那么程序将会把前五个有效数据保存在一个数组中,即7 19 -5 6 2,然后把这个数组中的值按逆序重新存放,即变成了2 6 -5 19 7,然后把它们打印出来。
输入格式:输入只有一行,包括若干个整数,最后一个整数是0。
输出格式:输出只有一行,包括若干个整数,即逆序排列后的结果。
输入输出样例
样例输入
7 19 -5 6 2 0
样例输出
2 6 -5 19 7
代码:
#include
#include
using namespace std;
void swap( int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void sort(int arr[],int left,int right)
{
int i=left;
int j=right;
while(i<j)
{ swap(arr[i],arr[j]);
i++;
j--;
}
}
int main()
{ int arr[20],count=0;
while(cin>>arr[count])//输入n个数,直到遇到0为止
{
if(arr[count]==0) break;
count++;
}
sort(arr,0,count-1);
for(int i=0;i<count;i++)
{ cout<<arr[i];
cout<<" ";
}
system("pause");
return 0;
}