了解递归解决方案以相反顺序打印出数组 [英] Understanding a recursive solution to print out an array in reversed order

查看:62
本文介绍了了解递归解决方案以相反顺序打印出数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++还是陌生的,从现在开始学习递归。我想以相反的顺序显示元素,而不必使用递归在末尾开始数组的索引。

I'm still new to C++ and as of right now learning recursion. I wanted to display the elements in reversed order without starting the index of the array at the end using recursion.

使用循环显然很容易,但是使用递归是另一回事。我在网上找到了解决该问题的解决方案,但无法理解它到底能够打印出每个值。

Obviously it would be very easy to do using loops, but using recursion is a different matter. I found this solution to the problem online, but can't understand how exactly its able to print out each value.

void recArrayBackPrint(int array[],int size)
{
   if (size > 0)
   {
      recArrayBackPrint(array+1,size-1);
      cout << array[0] << "   ";
   }
//  base case is empty array (size == 0), so do nothing
}

我了解在这种情况下,数组+ 1将指向位于当前元素+ 1处的内存地址。在尝试使用类似以下内容的方法跟踪它之后:

I understand that in this case, array + 1 would be referring to the memory address located at the current element + 1. After trying to trace it using something like:

int main() {
    int values[5] = {1,2,3,4,5}
    recArrayBackPrint(values,5);
}

我可以一直减小到0,但是仍然有我不知道它如何能够打印出array [4],array [3] ..等。在我看来,它应该是击中recArrayBackPrint并一直到大小0,然后什么也不做。

I can get all the way down to the size being 0, but still have no idea how it would be able to print out array[4], array[3].. etc. In my mind it should be hitting recArrayBackPrint and going all the way to size 0, then doing nothing at all.

那么这里到底发生了什么?

So what exactly is going on here?

推荐答案

第一次在 recArrayBackPrint ,它先打印{1,2,3,4,5}的第一个元素,然后打印1.

,但在输出之前,它进入第二个元素 recArrayBackPrint 打印{2,3,4,5}的第一个元素,然后打印2。

在输出2之前,第三个 recArrayBackPrint 打印{3,4,5}中的3。

一直到最后一个 recArrayBackPrint 打印{5}中的5。
,则输出顺序为:

5th recArrayBackPrint (5)

4th recArrayBackPrint (4)

3rd recArrayBackPrint (3)

2nd recArrayBackPrint (2)

1st recArrayBackPrint (1)

first time in recArrayBackPrint,it's printing the first element of {1,2,3,4,5},then 1.
but before the output, it enters the second recArrayBackPrint to print the first element of {2,3,4,5} ,then 2.
still, before output 2, the third recArrayBackPrint to print 3 in {3,4,5}.
and all the way to the last recArrayBackPrint to print 5 in {5}. then the output order is:
5th recArrayBackPrint (5)
4th recArrayBackPrint (4)
3rd recArrayBackPrint (3)
2nd recArrayBackPrint (2)
1st recArrayBackPrint (1)

我希望我能说清楚。

这篇关于了解递归解决方案以相反顺序打印出数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆