将数组中n个整数按相反顺序存放。

解:程序1

#include<stdio.h>

int inv(int x[], int n)

{

int temp, i, j, m = (n - 1) / 2;

for (i = 0; i <= m; i++)

{

j = n - 1 - i;

temp = x[i];

x[i] = x[j];

x[j] = temp;

}

return;

}


int main()

{

int i, a[10] = { 1,2,3,4,5,6,7,8,9,10 };

printf("The original array:\n");

for (i = 0; i < 10; i++)

{

printf("%d ", a[i]);

}

printf("\n");

inv(a, 10);

printf("The array has been inverted:\n");//inverted:反向的

for (i = 0; i < 10; i++)

{

printf("%d ", a[i]);

}

printf("\n");

return 0;

}

程序2:用指针变量作实参

 

#include<stdio.h>

int inv(int *x, int n)

{

int *p, temp, *i, *j, m = (n - 1) / 2;

//形参数组名x接收了实参数组首元素a[0]的地址

i = x; j = x + n - 1; p = x + m;

for (; i <= p; i++, j--)

{

temp = *i;

*i = *j;

*j = temp;

}

return;

}


int main()

{

int i, a[10] = { 1,2,3,4,5,6,7,8,9,10 };

printf("The original array:\n");

for (i = 0; i < 10; i++)

{

printf("%d ", a[i]);

}

printf("\n");

inv(a, 10);

printf("The array has been inverted:\n");//inverted:反向的

for (i = 0; i < 10; i++)

{

printf("%d ", a[i]);

}

printf("\n");

return 0;

}


结果:

he original array:

1 2 3 4 5 6 7 8 9 10

The array has been inverted:

10 9 8 7 6 5 4 3 2 1

请按任意键继续. . .