Home > Software design >  From iterative function to recursive function
From iterative function to recursive function

Time:03-20

Can someone help me transform this function from iterative form to recursive form?. I'll be very grateful, because I'm not very good at recursion. Thanks in advance. P.S my function turns vowels into the next letter of the alphabet, and consonants into the previous letter

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void modifyString( char vowels[], char string[]) {
    for (int i = 0; i < strlen(string); i  ) {
      string[i] = tolower(string[i]);
        if (strchr(vowels, string[i])) {
            string[i]  = 1;
        } else if (isalpha(string[i])) {
            string[i] -= 1;
        }
    }  
}


int main() {

    char vow[]="aeiou",str[100];

    printf("String : ");
    fgets(str,sizeof str,stdin);

   modifyString(vow,str);

   printf("new string : %s",str);
    return 0;
}

CodePudding user response:

/* The idea is you need some sort of relation between each
 * recursive calls. E.g. when you call modifyString(s),
 * you can manually modify the first character of s and let
 * the recursion handle the rest of the string.
 */
void modifyString( char vowels[], char string[]) {
    // The base case
    if (not string) return;

    // Now work on the first character
    string[0] = tolower(string[0]);
    if (strchr(vowels, string[0])) {
        string[0]  = 1;
    } else if (isalpha(string[0])) {
        string[0] -= 1;
    }

    // Recursive call, after which string 1 will have been modified.
    modifyString(vowels, string 1);
  •  Tags:  
  • c
  • Related