#include<iostream>
using namespace std;
int main(){
//元素逆置
//要求声明一个5个元素的数组,将数组逆置
//例如:数组{1,4,5,3,7} 最后输出为{7,3,5,4,1}
//分析:1.创建数组
// 2.实现逆置
// 3.打印输出逆置后的数组
//1.创建数组以及输出逆置前的数组
int arr[]={1,4,5,3,7};
cout<<"逆置前的数组为:"<<endl;
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
// 2.实现逆置 :
// 1>定义一个变量,记录起始下标的位置
// 2>定义一个变量,记录结束下标的位置
// 3>定义一个变量,暂时存放起始下标的值
// 4>实现起始下标和结束下标互换位置
// 5>起始下标++ 结束下标——
// 6>重复上述操作(用while循环)
// 7>直到起始下标>=结束下标结束循环
int start=0;
int end=sizeof(arr)/sizeof(arr[0])-1 ;
int temp=arr[start];
while(start<end){
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
cout<<"逆置后的数组为:"<<endl;
for(int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
C++实现元素逆置
最新推荐文章于 2024-04-05 20:27:46 发布