5.1.2 一维数组案例-元素逆置
示例:
#include <iostream>
using namespace std;
int main()
{
//逆置元素
int arr[5] = { 1,3,2,5,4 };
cout << "元素逆置前:" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i] << '\t';
}
cout << endl;
int start = 0;
//下面是常用的求数组最大下标的方法。
int end = sizeof(arr) / sizeof(arr[0]) - 1;
while (start < end)
{
//下面是常用的交换两元素的方法。
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
cout << "元素逆置后:" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i] << '\t';
}
cout << endl;
system("pause");
return 0;
}
两元素交换图解:
运行结果: