void display(char str[])
{
if (*str) {
putchar(*str);
display(str+1);
}
}
Recursive Function Loop Through Character Array
-
06-03-2022 - |
Question
I have an assignment where I'm supposed to loop through a Character Array using a Recursive Function. I figured it would be easy since I would know the length of the array but then the prototype is give to me which I have to use:
void display(char str[])
I can't imagine how I'm supposed to loop through this recursively without knowing the length. Can anybody give me a nudge on this please?
Solution
OTHER TIPS
C strings (assuming your character array is a C string) are assumed to be null terminated. So, you could, for instance, use a recursive function to compute the length and look for the null character for your base case to know you are done.
As mentioned by @abelenky and @Nathan, a character array is assumed to end with a "null" char (usually '\0'
).
Here's an example on how to find the number of characters
unsigned int strLen( const char[] str ) {
unsigned int len = 0;
while( str[len] ) {
len++;
}
return len;
}