# A3K4 << how many alpha characters and sum of digits?

• 11-30-2011
scatterbrain
A3K4 << how many alpha characters and sum of digits?
So I have to write a program counting the sum of digits, and the number of characters in a string... it looks like this. Oh, and it has to use corecursive functions, so that's why I used it if it seems inappropriate for this task.

Code:

```/*Corecursive Functions 11/29/11 */ #include <stdio.h> #include <string.h> #include <ctype.h> void count_alph(char * word, int i, int alphacount, int digitCount); void sum_digit(char * word, int j, int alphacount, int digitCount); int main() { char word[100];     /*String input prompt*/     printf("Input the word to be checked: \n");     scanf("%s", word);         count_alph(word,0,0,0,0); } void count_alph(char *word, int i, int alphacount, int digitCount) { while (i < strlen(word)) {     if (isalpha(word[i]))     {         alphacount++;         i++;         }     else         sum_digit(word, i, alphacount, digitCount);         }             printf("There are %d letters. ", alphacount);                         } void sum_digit(char *word, int j, int alphacount, int digitCount) { while (j < strlen(word)) {     if (isdigit(word[j]))     {         digitCount += (word[j] - '0');         j++;         }     else         count_alph(word, j, alphacount, digitCount);}                     printf("The sum of the digits is %d. ", digitCount);     }```

For some reason, when I input "b2b", it loops indefinitely, only printing "There are 2 letters." thousands of times. It's supposed to say: "There are two letters. The sum of the digits is 2."
• 11-30-2011
Tclausex
You've entered the recursion twilight zone. Perhaps someone who understands what exactly is happening can explain it, but you need to have a conditional return statement at the top of each function.
Code:

```if( i >= strlen(word) ) return ; ... if( j >= strlen(word) ) return ;```
Otherwise, your recursion will never unwind.

You'll need to change some of your other logic, but that should end the infinite looping.
• 12-01-2011
scatterbrain
Thanks man. That actually didn't work for me (or maybe I just didn't adjust my logic accordingly). But I got it to work by inserting break statements into the else statements. I'm still not sure why it needed those, but whatever. I'll keep investigating. Thanks for your reply.
• 12-01-2011
Tclausex
Well, notice that the logic flow changes as soon as I changed your while loop to an if(). So you've lost your looping. Change the following if() that was in your original while loop TO a while loop and remove the "else". No breaks needed.