nofe
nofe

Reputation: 408

I don't understand why this simple recursive function doesn't work in C

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. )

Upvotes: 1

Views: 173

Answers (4)

Trent
Trent

Reputation: 1109

This line has problems too:

if(string[index]<'a'||string[index]>'Z') return -1;

In the ASCII table, upper case letters come first, followed by several non-letter symbols, then the lower case letters. That line should look more like:

char l = string[index];
if(!((l >= 'A' && l <= 'Z') || (l >= 'a' && l <= 'z'))) return -1

Upvotes: 1

tzerb
tzerb

Reputation: 1433

try:

return only_letters(string, index+1); 

Upvotes: 0

Thomas
Thomas

Reputation: 17412

Uppercase letters come before lowercase letters in ASCII. The first letter of your second string is a lower-case 't' with an ASCII value of 116. 'Z' on the other hand has an ASCII value of 90, thus 't' > 'Z'

ASCII(Z) == 90
ASCII(a) == 97
ASCII(t) == 116

Upvotes: 0

Mat
Mat

Reputation: 206689

Please turn on your compiler warnings, you're not returning anything from that function in the default case.

return only_letters(string, index+1);

Other problem is that you've got your range inverted. Capital letters have lower ASCII values than lowercase ones.

And main must return int. Not void.

Upvotes: 3

Related Questions