C++数组逆置while循环
时间: 2024-09-14 13:10:36 浏览: 52
在C++中,你可以使用while循环来逆置数组。数组逆置意味着将数组中的元素从头到尾或从尾到头进行交换。下面是一个简单的示例,展示如何使用while循环来逆置一个整数数组:
```cpp
#include <iostream>
void reverseArray(int arr[], int start, int end) {
while (start < end) { // 当起始索引小于结束索引时继续
// 交换arr[start]和arr[end]
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// 移动索引
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i : arr) {
std::cout << i << " ";
}
reverseArray(arr, 0, size - 1); // 逆置整个数组
std::cout << "\nReversed array: ";
for (int i : arr) {
std::cout << i << " ";
}
return 0;
}
```
在这个例子中,`reverseArray`函数接受一个数组、起始索引和结束索引作为参数,通过不断交换这两个索引处的元素,直到它们相遇,实现了数组的逆置。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)