Easy points for anyone who follows directions and posts a working program that I
ID: 3544383 • Letter: E
Question
Easy points for anyone who follows directions and posts a working program that I can run in unix. Must be written in C. Thank you!
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.
Explanation / Answer
#include<stdio.h>
#include<string.h>
void sum_digit(char* str,int begin);
int count_alph(char* str,int begin)
{
static int number_of_chars = 0;
while((str[begin]>=65 && str[begin]<=90) || (str[begin]>=97 && str[begin]<=122))
{
number_of_chars++;
begin++;
}
if(str[begin]!='')
sum_digit(str,begin);
return number_of_chars;
}
void sum_digit(char* str,int begin)
{
static int sum = 0;
while(str[begin]>=48 && str[begin]<=57)
{
sum = sum + str[begin]-'0';
begin++;
}
if(str[begin]!='')
count_alph(str,begin);
else
printf(" Sum of digits is : %d",sum);
}
void direct_calc(char* str,int *no_of_chars,int *sum)
{
int i;
*sum =0;
*no_of_chars=0;
for(i=0; str[i]!=''; i++)
{
if(str[i]>=48 && str[i]<=57)
*sum = *sum + str[i]-'0';
else if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122))
{
(*no_of_chars)++;
}
}
}
int main()
{
char *str = "A0is444apple9";
int no_of_chars = 0;
int sum = 0;
printf(" Using CO-Recursive Method :");
printf(" Number of alphabetic characters : %d", count_alph(str,0));
direct_calc(str,&no_of_chars, &sum);
printf(" Using Direct Method :");
printf(" Number of alphabetic characters : %d",no_of_chars);
printf(" Sum of digits is : %d",sum);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.