这个递归程序如何反转所有字符

时间:2017-10-22 09:51:25

标签: c recursion

#include <stdio.h>
void reverseSentence();

int main()
{
    printf("Enter a sentence: ");
    reverseSentence();

    return 0;
}

void reverseSentence()
{
    char c;
    scanf("%c", &c);

    if( c != '\n')
    {
        reverseSentence();
        printf("%c",c);
    }
}

我知道该函数可以存储用户输入的所有字母,直到最后一个'\ n'字符。但是,我不知道程序如何打印最后一个字符并返回reverseSentence(),直到它打印出第一个字母。任何人都可以帮助解释一下吗?

1 个答案:

答案 0 :(得分:0)

有多种方法可以反转数组的字符。这是我的代码,要反转一个字符串,我希望它有助于回答你的问题。

#include<stdio.h>
#include<string.h>

int main()

{
  char string[]="Reverse String";
  char new[20];
  int count=0;
  int i,j;
  i=0;
  j=strlen(string)-1;

 while(string[count]!='\0')
  {
    new[i]=string[j];
    i++;
    j--;
    count++;
  }
 printf("%s\n",new);

  for(i=0;i<strlen(string);i++)
   {
    printf("%c",new[i]);
   } 
}