Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

From iterative function to recursive function

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/* 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading