Reputation: 161
The task is to write a recursive function which returns the last number (ASCII) in a char array. If there is no number in a given array it should return 0.
Edit
In this case the function should only return '4' from array a, because it is the last digit in that array and in array b it should return '0', because there is no digit at all in that array.
char rek(char a[], int i){
int j = i;
char tmp = '0';
if((a[j] >= '0') && (a[j] <= '9')){
tmp = a[j];
}
while(a[j] != '\0'){
rek(a, i+1);
}
return tmp;
}
int main(){
char a[7] = {'a','b','1','c','4','n','\0'};
char b[7] = {'a','b','c','c','a','n','\0'};
printf("Letzte Ziffer: %c \n", rek(a, 0));
printf("Letzte Ziffer: %c", rek(b, 0));
getchar();
return 0;
}
I understand that everytime my function is recursively called tmp is set to '0' which is not what i want.
Somehow i can't figure out, how the function can call itself with the next element in the array to look at, without losing the set tmp value.
I also don't want to make tmp a global variable.
Furthermore what was unexpected to me, it outputs 'c' as result in bot lines. I thought my if-statement should prevent that.
Upvotes: 0
Views: 1727
Reputation: 12732
Call the function recursively until you reach \0
.
And consider return value of recursive call.
char rek(char a[]){
char ret = '0';
if (*a != '\0')
ret = rek(a+1);
if((*a >= '0') && (*a <= '9') && ret == '0'){
ret = *a;
}
return ret ;
}
Upvotes: 2
Reputation: 12669
Whenever using recursion, try to implement tail recursion because tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler.
Using tail recursion, you can do:
#include <stdio.h>
char rek(char a[], char i){
if (*a == '\0')
return i;
if ((*a >= '0') && (*a <= '9'))
i = *a;
return rek(++a, i);
}
int main(){
char a[7] = {'a','b','1','c','4','n','\0'};
char b[7] = {'a','b','c','c','a','n','\0'};
printf("Letzte Ziffer: %c \n", rek(a, '0'));
printf("Letzte Ziffer: %c", rek(b, '0'));
getchar();
return 0;
}
Upvotes: 2
Reputation: 727
You need to understand recursion. Try to read abit about it. There are no need for the while loop. Also the array index is redundant since it's recursive. Then try to understand this:
#include <stdio.h>
char rek(char a[]){
if(*a != 0){ /* If we are not at the end of the string ... */
char tmp = rek(a + 1); /*... do a recursive call at the next char.*/
if(tmp) return tmp; /* If there are numbers later in the string return that. */
}
if((*a >= '0') && (*a <= '9'))
return *a;
else
return 0;
}
int main(){
char a[7] = {'a','b','1','c','4','n','\0'};
char b[7] = {'a','b','c','c','a','n','\0'};
printf("Letzte Ziffer: %c \n", rek(a));
printf("Letzte Ziffer: %c", rek(b));
return 0;
}
You should also note that using recursion for this problem is only for pedagogic reasons. This problem is better solved with a simple loop.
Upvotes: 1