数组元素交换:编写一个函数函数的功能是交换数组中指定位置的两个元素的值(例如下标为3的和下标为1的数组元素交换位置)。可以在main中创建一个整型数组,并调用该函数来进行元素交换,然后输出交换后的数组。
时间: 2024-02-12 11:07:24 浏览: 53
好的,以下是实现该功能的C++代码:
```cpp
#include <iostream>
using namespace std;
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(arr[0]);
cout << "原始数组:";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
swap(arr, 1, 3);
cout << "交换后的数组:";
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
在上面的代码中,swap函数接收一个整型数组及两个指定位置的下标作为参数,然后交换这两个位置的元素值。
在main函数中,我们首先创建了一个包含5个整数的数组,并输出原始数组。然后,我们调用swap函数交换了下标为1和下标为3的元素。最后,我们再次输出交换后的数组。
运行程序,输出如下:
```
原始数组:1 2 3 4 5
交换后的数组:1 4 3 2 5
```
可以看到,交换后的数组中下标为1和下标为3的元素位置已经发生了交换。