this is my first time playing with recursive functions, and this function that I wrote returns the size of a string if it contains only letters in ascending order, and if not it returns -1.
I don't understand why it works for both codes, after I took out the second "return". Is one more wasteful than the other? Would appreciate some insight.
with "return only_ascending_letters(string, index+1);"
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
return only_ascending_letters(string, index+1);
else return -1;
}
with "only_ascending_letters(string, index+1);"
#include <stdio.h>
int only_ascending_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="aabcdefg";
printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));
}
int only_ascending_letters(char string[], int index){
if(!string[index]) return index;
if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1]))
/*Took out the return*/ only_ascending_letters(string, index+1);
else return -1;
}