简体   繁体   English

C-反转句子-递归-无数组

[英]C - Reversing a sentence - Recursion - Without Array

void reverse()
{
    char c;
    scanf("%c", &c);
    if(c!='\n')
    {
        reverse();
        printf("%c", c);
    }
}

When 'c==\\n', the program doesn't even get inside the 'if' block. 当'c == \\ n'时,程序甚至没有进入'if'块内。 Then how does it print the converted sentence in the end. 然后如何最终打印转换后的句子。 Please explain where the 'return' happens and also to where it gets returned. 请说明“返回”发生的位置以及返回的位置。

当'c == \\ n'时,它将是递归的结尾,该函数将不再进一步调用自身并返回到最后一个调用,该调用在'printf(“%c”,c)'行中继续,从而打印字符串的最后一个字符,然后返回到第二个最后一个调用,依此类推。

Let's run the code by hand. 让我们手动运行代码。 Imagine we input "foobar" . 假设我们输入"foobar" We'll right down every instruction the computer processes. 我们将整理计算机处理的每条指令。 If we recurse, we'll just indent as we keep track of things. 如果我们递归,那么我们会在跟踪事物时缩进。 If we do that, we can see the sequence of instructions executed is: 如果这样做,我们可以看到执行的指令顺序为:

scanf() // reads 'f'
if ('f' != '\n')
  scanf() // reads 'o'
  if ('o' != '\n')
    scanf() // reads 'o'
    if ('o' != '\n')
      scanf() // reads 'b'
      if ('b' != '\n')
        scanf() // reads 'a'
        if ('a' != '\n')
          scanf() // reads 'r'
          if ('r' != '\n')
            scanf() // reads '\n'
            if ('\n' != '\n')
          printf('r')
        print('a')
      print('b')
    print('o')
  print('o')
print('f')

Each indentation is a recursive call to reverse() . 每个缩进都是对reverse()的递归调用。 As you can see, the sequence of printf() commands are the reverse of the input "foobar" . 如您所见, printf()命令的顺序与输入"foobar"的顺序相反。

Hopefully this gives some insights as to how it works. 希望这对它如何工作提供了一些见解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM