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).
nis 0,charArray[n-1]is undefined. Do the test first.