Problem:
A function that calls another function, which in turn calls the original function, is said to be
corecursive. Note that corecursive functions occur in pairs. Write a program that counts the number of
alphabetic characters in a string and sums the digits in the string. For example, the string
"AOis444apple7" has eight alphabetic characters, and the digits in the string sum to 19. Write a pair of
corecursive functions to help carry out the tasks. Use count_alph() to count the alphabetic characters,
and use sum_digit() for summing the digits. These two functions should call each other. For
comparison, write a non-corecursive function that performs the two tasks in a direct, more natural
fashion. Hint: If necessary, use static variables.
Grading
Code:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int countAlpha(char *);// counts all alpha chars
int sumDigits(char *);// finds digits and sums
int main(void){
char s[]=("AOis444apple7"); //string being tested
countAlpha(s);// calls string to alpha count
}
int countAlpha(char *s)
{
int i;//counter
int countAlpha=0;
for(i=0;i<13;i++) {//checks all chars strlen of s
if(isalpha(s[i])){//if it is an alpha char
countAlpha++;}//it adds 1 to count alpha
}
printf("There are %d letters.", //alpha total
countAlpha);
sumDigits(s);//calls to sumdigits function in count alpha
return countAlpha;
}
int sumDigits(char *s)
{
int sum=0;
int total=0;
int i;
for(i=0;i<13;i++) {//tests string finds digits
total=sum+(isdigit(*s));// finds the digit but for some reason cant pull value of that point to sum
s++;
}
printf("and the sum of the digits is %d\n",
total);
return sumDigits;
}
Im having trouble finding the sum of the digits after finding the digits in the string. My friend in class said using atoi, but i was wondering if there was a simpler solution? Didnt mean to make it sound like im dumping the problem and waiting for someone to solve it. Im just looking for advice.