c语言利用一维数组 元素变长 宏定义)将一个数组按逆序重新排序
时间: 2023-10-07 09:07:44 浏览: 86
可以使用以下的宏定义来实现将一个数组按逆序重新排序:
```c
#define REVERSE(arr, n) do { \
int i, j; \
for (i = 0, j = n - 1; i < j; i++, j--) { \
int temp = arr[i]; \
arr[i] = arr[j]; \
arr[j] = temp; \
} \
} while (0)
```
其中,`arr` 表示要进行逆序排序的数组名,`n` 表示数组的元素个数。这个宏定义使用了一个 `do...while` 循环结构,来实现将数组按逆序重新排序的功能。在循环体中,使用了两个指针 `i` 和 `j` 分别从数组的头部和尾部开始遍历,然后交换它们所指向的元素,直到指针相遇为止。
相关问题
C语言定义一个数组al6],将该数组中的元素值按逆序重新存放
您好,这是一个关于C语言数组的问题。可以使用以下代码将数组中的元素按逆序重新存放:
```
#include <stdio.h>
#define SIZE 6
int main() {
int arr[SIZE] = {1, 2, 3, 4, 5, 6};
int temp;
for (int i = 0; i < SIZE / 2; i++) {
temp = arr[i];
arr[i] = arr[SIZE - i - 1];
arr[SIZE - i - 1] = temp;
}
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
该程序中,利用循环从数组两侧开始逐个交换元素的值,最终按照逆序重新存储到数组中。
希望这能帮到您!
用c语言数组编写程序将一维数组中的元素重新按逆序存放在原数组中,且只定义一个数组
以下是用C语言实现将一维数组中的元素重新按逆序存放在原数组中的程序:
```c
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE], n, i, temp;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
// Reversing the array
for(i=0; i<n/2; i++)
{
temp = arr[i];
arr[i] = arr[n-1-i];
arr[n-1-i] = temp;
}
printf("The array after reversing is:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
```
在这个程序中,我们使用了一个名为`arr`的一维整型数组,它的大小为`MAX_SIZE`。用户输入数组的大小和元素,然后程序将数组按逆序重新排列,最后输出排列后的数组。
我们使用一个`for`循环来遍历数组,并使用一个`temp`变量来交换数组的元素,从而实现数组的逆序排列。