0

I'm studying for an exam in C, and I struggled today implementing what I was told with recursion, I did implement it with iterative function though, and then I somehow discovered that I could easily make it recursive. for example: (the purpose of the function is to find from right to left the chars betweem 0-9, transform them from char to int and print them in that order)

Example:

char chArray[] = { '2','4','e','b','c','@','0' };
    printf("%d", buildNumber_rec(chArray, 7));

Iterative:

int buildNumber(char chArray[], int n){
    int i,num=0;
    for(i=0;i<n;i++)
        if(chArray[i]>='0' && chArray[i]<='9')
            num=10*num + (chArray[i]-'0');
    return num;
}

Recursive:

int buildNumber_rec (char chArray[], int n){
    char last=chArray[n-1];
    if(!n) return 0;
    if(last>='0' && last<='9')
        return (last-'0')+10*buildNumber_rec(chArray,n-1);
    return buildNumber_rec(chArray,n-1);
}

Output:

240

I know it sounds too general, but is it possible to get the idea of how to solve recursive exercises by first implementing them with iterative function? In other words, discovering the pattern of how to solve recursively by first doing iteratively (If, of curse, this is my only choice - meaning, I don't know how to solve it recursively).

11
  • Think of recursion like iteratively operating with a stack data structure. Commented Mar 1, 2016 at 16:42
  • 1
    "how to solve recursive exercises by first implementing them with iterative function" - not so clear what does this mean, mind to elaborate? Commented Mar 1, 2016 at 16:42
  • 1
    Note that if n is 0, charArray[n-1] is undefined. Do the test first. Commented Mar 1, 2016 at 16:43
  • 1
    Normally one tries to avoid recursion and does it the other way around: re-implement a recursive algorithm using iteration. Reason is to get rid of the stack. Modern compilers typically automatically convert tail-recursion to an iterative loop. Commented Mar 1, 2016 at 16:48
  • 1
    @IlanAizelmanWS OK, given your example and my own experience. Short answer is: I think it is possible, but I am not sure if it is always possible Commented Mar 1, 2016 at 16:48

1 Answer 1

1

Doing something iteratively first is fine to help you gain an understanding of the solution to a problem. Once you understand that, then you can refactor it to a recursive function later on. If that helps you understand everything, then that is fine. Understanding what is going on is the important part, not which order you do it in.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.