[英]Recursion using C language
当我编译该程序时,我只会得到第一个大写字母,而其余的则不会。
ABldjfdslkjfCK
我只会得到“ A”吗?
#include <stdio.h>
#include <string.h>
FILE *fp;
int main(void)
{
int size;
char input[100]; // array size of 100
if (fp = fopen("message.txt","r")) // file exists
{
fgets(input,100,fp);// scans the sentence.
}
else
{
printf("file not found");// if there is no such a file.
}
size=strlen(input);
recursive(size,input);
return 0;
}
int recursive(int size, char array[])
{
static int index = 0; // static so when the function is called, the value is kept
if (index < size) // start from index 0 until the size-1
{
if (array[index] >= 'A' && array[index] <= 'Z') // check for A to Z (CAPITALIZE CHARACTERS only)
{
printf("%c\n", array[index]); // print it
}
else
{
return recursive(size,array); // calls the function (recursion)
}
}
return 0;
}
您永远不会增加index
的值。 此外,如果当前字符是大写字母,则不要调用recursive
函数,因此该函数仅返回。
与其将静态变量用作index
,不如将其作为recursive
传递给参数; 否则,该函数是不可重入的。
您的递归函数仅在找到非大写字符时才调用自身。 当找到第一个大写字母时,将其打印并退出
您当前的函数仅打印A
因为一旦找到大写字母(在您的情况下为A
),它将返回0。
还有其他问题,所以我将这样重写函数:
#include <ctype.h> /* for isupper */
void recursive(const char* s)
{
/* stop condition: empty string */
if (s[0] == '\0')
return;
/* main body: print letter if capital */
if (isupper(s[0]))
printf("%c\n", s[0]);
/* recursion: advance to the next character */
recursive(s + 1);
}
像这样使用它: recursive(input)
。
递归函数具有的其他问题是index
变量是静态的。 在当前版本中,这不是问题,因为除了琐碎的方式之外,您实际上并未使用它。 但是一旦尝试解决其他问题(可能导致您以更复杂的方式使用index
),使其static
将带来一些问题:
两个问题:
我看到的第一个错误是您永远不会增加索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.