编程实现将数组中的元素按照相反顺序存放
时间: 2024-05-08 20:16:56 浏览: 19
以下是Python语言实现的代码:
```python
arr = [1, 2, 3, 4, 5]
reverse_arr = arr[::-1]
print(reverse_arr) # 输出 [5, 4, 3, 2, 1]
```
其中,`[::-1]`表示将数组从后向前每隔一个位置取一个元素,即相当于将数组倒序排列。
相关问题
c语言编程实现将数组中的元素按照相反顺序存放
```c
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE], reversed[MAX_SIZE];
int size, i, j;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Reverse the array
for (i = size - 1, j = 0; i >= 0; i--, j++) {
reversed[j] = arr[i];
}
// Print the reversed array
printf("The reversed array is:\n");
for (i = 0; i < size; i++) {
printf("%d ", reversed[i]);
}
printf("\n");
return 0;
}
```
将数组a中8个整数按相反顺序存放,用指针变量作实参。要求用C语言编程。
以下是将数组a中8个整数按相反顺序存放的C语言代码:
```
#include <stdio.h>
void reverse_array(int *p, int size) {
int temp;
for(int i = 0; i < size/2; i++) {
temp = *(p+i);
*(p+i) = *(p+size-1-i);
*(p+size-1-i) = temp;
}
}
int main() {
int a[8] = {1, 2, 3, 4, 5, 6, 7, 8};
reverse_array(a, 8);
for(int i = 0; i < 8; i++) {
printf("%d ", a[i]);
}
return 0;
}
```
在main函数中,我们定义了一个长度为8的整型数组a,并将其初始化为{1, 2, 3, 4, 5, 6, 7, 8}。我们将数组a的地址和数组长度作为参数传递给reverse_array函数。
在reverse_array函数中,我们使用一个循环来遍历数组的前一半元素,并交换每一对元素的值。我们使用指针变量p来访问数组元素的值。最后,当循环结束后,数组a中的元素就被按相反顺序存放了。
在main函数中,我们再次遍历数组a,输出结果为{8, 7, 6, 5, 4, 3, 2, 1}。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)