c++实现数组元素逆置
例如:请声明一个5个元素的数组,并且将元素逆置.
(如原数组元素为:1,3,2,5,4;逆置后输出结果为:4,5,2,3,1);
#include <iostream>
#include <string>
using namespace std;
int main() {
int a[5] = { 22,33,11,4,555 };
int t;
cout << "转置前的数组:" << endl;
for (int i = 0; i < 5; i++) {
cout << a[i] <<" ";
}
cout << endl;
cout << "转置后的数组:" << endl;
int strat = 0;
int end = sizeof(a) / sizeof(a[0]) - 1;//数组结束下标,不用自己计算数组大小,方便修改
//实现逆置
//1.起始 结束位置 元素互换
//2.起始位置++ 结束位置--
//3.循环1 直到起始位置 >= 结束位置
for (int i = 0; i < 5; i++) {
if (strat < end){
t = a[strat];
a[strat] = a[end];
a[end] = t;
}
strat++;
end--;
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}