数组元素逆序存放,两种解题思路

练习03-16-01

输出样例:

The array a :
 -3  0  6 -1  3  0 -3  2 -1 -1
The inverted array a :
 -1 -1  2 -3  0  3 -1  6  0 -3
--------------------------------
Process exited after 0.02617 seconds with return value 0
请按任意键继续. . .

代码一:

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
	srand((unsigned)time(NULL));
	int a[10],i;
	printf("The array a :\n");
	for(i=0;i<10;++i){
		a[i]=rand()%10-3;
		printf("%3d",a[i]);
	}
	void inv(int x[],int n);
	inv(a,10);
	printf("\nThe inverted array a :\n");
	for(i=0;i<10;++i){
		//a[i]=rand()%10-3;
		printf("%3d",a[i]);
	}
	return 0;
}
void inv(int x[],int n)
{
	int i=0,j=n-1,m=(n-1)/2,temp;
	for(i;i<=m;++i){
		j=n-1-i;
		temp=x[i];
		x[i]=x[j];
		x[j]=temp;
	}
}

代码二:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	void inv(int *x,int n);
	srand((unsigned)time(NULL));
	int a[10],i;
	printf("The original array:\n");
	for(i=0;i<10;++i){
		a[i]=rand()%19;
		printf("%3d",a[i]);
	}
	
	inv(a,10);
	printf("\nThe inverted array a:\n");
	for(i=0;i<10;++i){
		printf("%3d",a[i]);
	}
	return 0;
}
void inv(int *x,int n)
{
	int *i=x,*j=x+n-1,temp;
	int *l=x+(n-1)/2;
	for(i;i<=l;++i,--j){
		//j=x+n-1-i;
		temp=*j;
		*j=*i;
		*i=temp;
	}
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值