Author Topic: Help with Corecursion in C - Problem Solved, Locking  (Read 327 times)

Code: [Select]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>

void count_alph(char str[], int *ltrs, int *sm, int index);
void sum_digit(char str[], int *ltrs, int *sm, int index);

void main (void)
{
   char word[50];
   int sum = 0, letters = 0;

   printf("Enter a series of letters and numbers (50 character max):  ");
   scanf("%s", word);

   count_alph(word, &letters, &sum, 0);

   printf("\nThere are %d letters and the sum of the numbers contained is %d.", letters, sum);
   getch();
}

//count alphabetical elements of array
void count_alph(char str[], int *ltrs, int *sm, int index)
{
   // valid index?
   if (index < strlen(str))
   {
        // alphabetical?
if (isalpha(str[index]))
        {
           // increase number of letters
       *ltrs = *ltrs + 1;
             // check the next one
             count_alph(str, ltrs, sm, index++);
}
        else
        {
           // it's a number, handle accordingly
           sum_digit(str, ltrs, sm, index);
        }
    }
}

// sum digits in the array
void sum_digit(char str[], int *ltrs, int *sm, int index)
{
   // valid index?
   if (index < strlen(str))
   {
   // digit?
if (isdigit(str[index]))
        {
           // add the nimber to running sum
             *sm += str[index] - '0';
             // process the next one
             sum_digit(str, ltrs, sm, index++);
         }
         else
           // it's a letter, handle accordingly
           count_alph(str, ltrs, sm, index);
    }
}

I wind up getting this.

The error seems to spring up in whatever function the type of the first element is.  For instance, if I input "6tF" the error is in the sum function, and if I input "FFTTreyrty7" the error is in the alpha function.

Any and all help appreciated.  I don't even need to know how to fix it if you can just tell me what I did wrong.

Many thanks.

EDIT:
After messing around with it I see that I have infinite recursion.  If anyone wants to point out where I muffed up I'd be appreciative.
EDIT2:
I'm an idiot.  index++ should by ++index.
Thanks for nothing/making me figure it out on my own.  Locking.
« Last Edit: November 21, 2014, 09:22:18 PM by Plethora »