Home > Back-end >  How can I convert this method to become recursive?
How can I convert this method to become recursive?

Time:12-03

Method checks for the amount of each character and if its even for every character, it returns 1. Otherwise, it returns 0. String is passed via str[]. chars[] has its every value set to one at the start. It's hard to picture this becoming recursive, any help on teaching is appreciated.

int recursionCheckEven(int i, int j, char str[], int chars[20]) {
    for (i = 0; i < strlen(str); i =2) {
        int count = 0;
        for (j = i; j < strlen(str); j =2) {
            if (str[i] == str[j] && chars[j] == 1) {
                count  ;
                chars[i] = 2;
                chars[j] = 2;
            }
        }
        if (count % 2 != 0) {
            chars[i] = 0;
        }
    }
    for (int k = 0; k < 20; k  ) {
        if (chars[k] == 0) {
            return 0;
            break;
        }
    }
    return 1;
}

How I call this:

for (unsigned int i = 0; i < stringcount; i  ) {
        int chars[20] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
        if(recursionCheckEven(0, 0, strings[i], chars)) {
            printf("The %dth string has even number of characters\n", i);
        }
    }

CodePudding user response:

You can use a loop to go through the characters in a non-recursive way (this is recommended). The idea of recursion is to avoid using a loop (which is actually not recommended and wastes stack memory and causes other problems).

For recursive check, you can use pointers the check each element, then go to the next element and use the same function.

To help you get started, this is a recursive function which takes a string and counts the number of each character.

int recursive(int total, char* ptr, char ch)
{
    if (*ptr == '\0')
        return total;
    if (*ptr == ch)
        total  ;
    return recursive(total, ptr   1, ch);
}

int main(void)
{
    char *str = "111";
    char ch = '1';
    int total = recursive(0, str, ch);
    printf("total of char %c in %s: %d\n", ch, str, total);
    return 0;
}
  • Related