Reputation: 91
Is it possible to set an index inside a recursion without sending a null parameter?
example:
void checkArry(char str[],int len){
if(str[index] == 'P')
printf("P");
if(index != len)
checkArry(str,len);
}
How can I set that index to start from 0 and keep adding 1 to it without it being initialized each run?
Upvotes: 1
Views: 77
Reputation: 51423
Pass the index as parameter, and increment for each recursive call:
void checkArry(char str[],int len, int index){
if(str[index] == 'P')
printf("P");
if(index != len)
checkArry(str,len, index + 1);
}
and called with checkArry(str, len, 0);
If you do not want to add the extra index parameter, just use the len
variable instead, and go through the array in reverse:
void checkArry(char str[],int len){
if(len >= 0){
if(str[len] == 'P')
printf("P");
checkArry(str, len - 1);
}
}
Make sure you call the function correctly
checkArry(str, strlen(str) - 1);
We should start by the last character, hence strlen(str) - 1
.
If for some reason you do not want to print in reverse, then you can use this version, which will print from 0 to length
:
void checkArry(char str[],int len){
if(len >= 0){
checkArry(str, len - 1);
if(str[len] == 'P')
printf("P");
}
}
Upvotes: 1