I’m trying to write a simple function for a larger assignment I am writing in C.
The purpose of the function is to determine whether a string contains only lowercase or uppercase letters, and returns the size of the string (index of \0) if it passes the test, and -1 if it doesn’t.
This is what i’ve written:
#include <stdio.h>
int only_letters(char string[], int index);
void main() {
char string1[]="Hi my name is pete";
char string2[]="thisissupposedtobevalid";
printf("the first string is %d and the second one is %d\n",only_letters(string1,0),only_letters(string2,0));
}
int only_letters(char string[], int index){
if(!string[index]) return index;
if(string[index]<'a'||string[index]>'Z') return -1;
only_letters(string, index+1);
}
When I run this i am getting -1 for both the first string (which is supposed to be invalid) but also the second string, which is supposed to be valid.
(We’re not allowed to use loops and we have a dozen other limitations, so please don’t offer easier or simpler solutions, I know they exist but I am trying to understand why what I wrote doesn’t work. )
Please turn on your compiler warnings, you’re not returning anything from that function in the default case.
Other problem is that you’ve got your range inverted. Capital letters have lower ASCII values than lowercase ones.
And
mainmust returnint. Notvoid.