【C++】元素逆置

本文介绍了一种使用C++实现数组逆置的方法。通过定义一个包含五个元素的数组,并利用循环交换首尾元素的方式实现了数组逆置。文章展示了逆置前后的数组输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:
1、创建数组
2、实现逆置
2.1标记起始、终点位置
2.2将起始位置的数据另存
2.3起始位和终点位置互换,终点位存入2.2中的数据
3、输出逆置后的数组

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
//元素逆置
int main()
{
	int arr[5] = { 5,1,3,2,4 };
	cout << "The array before transpose is as follows:" << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << arr[i] << " ";
	}
	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;
	cout << "The array after transpose is as follows:" << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << arr[i] << " ";
	}
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值