【C++一维数组的元素逆置】

1.对于给定的元素的逆置:

#include <iostream>

using namespace std;

int main(){
int arr[5]={1,2,3,4,5}; //数组元素给定
	int start=0;  //记录数组的第一个位置的标
	int end=sizeof(arr)/sizeof(arr[0]) - 1 ;  //记录数组的最后一个位置的数 
	int count=end;
	int temp=arr[start];  //申请一个空间,做中转 
	while(start<end){
		temp=arr[start];
		arr[start]=arr[end];
		arr[end]=temp;
		start++;
		end--; 
	}
	
	for(int i=0; i<=count;i++){
		cout<<arr[i]<<" ";
		
	}

}

2.对于随机输入一维数组的数据:

#include <iostream>

using namespace std;


int main(){
	//输入数据:
	int num=0;  //接受用户输入的数据
	
	int arr[100];  // 定义一个一维数组,存储数据
	
	int count = 0;  //统计输入的数据的个数 
	
	
	//输入元素 
	cout<<"请输入你要输入的数据(输入-1表示结束):"<<endl;
	
	cin>>num;
	
	int i=0; 
	
	while(num!=-1){
		
		arr[i]=num;
		
		i++;
		
		cin>>num;
		
		count++;  

	}
	
	//输出逆置前的元素 
	cout <<"您输入的数据是:";
	for(int i=0; i<=count-1; i++){
		
		cout <<arr[i]<<" ";
	}  
	
	
	cout << endl;
	
	
	//元素的逆置
	int start=0;  //用于标记开始时的第一个元素的下标
	
	int end=count -1;  //用于标记最后一个元素的下标 
	
	int temp;  //定义一个新的变量,用于元素的交换 
	
	while(start<end){
		
		temp=arr[start];
		
		arr[start]=arr[end];
		
		arr[end]=temp;
		
		start++;
		
		end--;

	}
	
	//输出逆置后的元素 
	 
	 cout<<"逆置后的元素顺序为:"<<endl;
	for(int i=0; i<=count-1; i++){
		cout <<arr[i]<<" ";
	}  
	
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值