c语言实现数组反转,C语言使用递归算法反转数组

I was having some problem when trying to do a reverse array using recursion. Here is the function prototype:

void rReverseAr(int ar[ ], int size);

And here is my code:

int main()

{

int ar[10], size, i;

printf("Enter array size: ");

scanf("%d", &size);

printf("Enter %d numbers: ", size);

for (i = 0; i

scanf("%d", &ar[i]);

rReverseAr(ar, size);

printf("rReverseAr(): ");

for (i = 0; i

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

return 0;

}

void rReverseAr(int ar[], int size) {

int start = 0, end = size - 1, temp;

if (start < end) {

temp = ar[start];

ar[start] = ar[end];

ar[end] = temp;

start++;

end--;

rReverseAr(ar, size - 1);

}

}

The expected output should be when user entered 1 2 3 and it supposed to return 3 2 1. However, with these code, the output that I am getting is 2 3 1.

Any ideas?

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

Your code is almost right. The only problem is that instead of "shrinking" the array from both sides, you shrink it only from the back.

The recursive invocation should look like this:

rReverseAr(ar + 1, size - 2);

You do not need to increment start or decrement end, because their values are not used after modification.

# Answer 2

A Simple way :

#include

using namespace std;

void revs(int i, int n, int arr[])

{

if(i==n)

{

return ;

}

else

{

revs(i+1, n, arr);

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

}

}

int main()

{

int i, n, arr[10];

scanf("%d", &n);

for(i=0; i

{

scanf("%d", &arr[i]);

}

revs(0, n, arr);

return 0;

}

Iterate array with recursion in C : link

# Answer 3

What you are doing is to exchange values of the 1st and last elements and do the recursion.

Every time you should move your address to the next element as the starter for the next array exchange.

A possible way:

void rReverseAr(int ar[], int size){

int buffer=ar[0];

ar[0] = ar[size-1];

ar[size-1] = buffer;

if ((size!=2)&&(size!=1)) rReverseAr(ar+1,size-2);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值