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.