将数组a中n个数反序排列
要求如图:
思路
类似于两车速度一样的相遇问题。
方法1:数组法
(1)while循环
#include <stdio.h>
#define N 10
int main()
{
int a[N]={1,2,3,4,5,6,8,8,9,10};
int temp,i,j;
i=0; j=N-1;
while(i<=j)
{
temp=a[i]; a[i]=a[j]; a[j]=temp;
i++; j--;
}
for(i=0;i<N;i++)
printf("%d,",a[i]);
}
(2)for循环
#include <stdio.h>
#define N 10
int main()
{
int a[N]={1,2,3,4,5,6,8,8,9,10};
int temp,i,j;
for(i=0,j=N-1;i<=j;i++,j--)
{
temp=a[i]; a[i]=a[j]; a[j]=temp;
}
for(i=0;i<N;i++)
printf("%d,",a[i]);
}
方法2:指针法
(1)while循环
#include <stdio.h>
#define N 10
int main()
{
int a[N]={1,2,3,4,5,6,8,8,9,10},i;
int temp,*p,*q;
p=a;q=a+N-1;
while(p<=q)
{
temp=*p; *p=*q; *q=temp;
p++; q--;
}
for(i=0;i<N;i++)
printf("%d,",a[i]);
}
(2)for循环
#include <stdio.h>
#define N 10
int main()
{
int a[N]={1,2,3,4,5,6,8,8,9,10},i;
int temp,*p,*q;
for(p=a,q=a+N-1;p<=q;p++,q--)
{
temp=*p; *p=*q; *q=temp;
}
for(i=0;i<N;i++)
printf("%d,",a[i]);
}