Start off by always using curly brackets, even when it's only a single statement:
if (condition)
{
doSomething();
}
It can prevent a lot of head scratching when you edit your code and it looks like it should work:
if (condition)
doSomething();
doSomethingElse();
That's not the same as:
if (condition)
{
doSomething();
doSomethingElse();
}
Then look at what you have written: it's about right for starters!
int rangeIndex(char c)
{
if (c >= 'a' && c <= 'i')
{
return 0;
}
...
}
That code returns zero if the character is your "Low range".
So all you have to do is duplicate it, change the range, and change the value you return.
I'd add a third return statement at the end in case it's not in either range myself, perhaps returning -1?
Give it a try: it's pretty simple!
"i did what you wrote, but again my main problem is i can't use if statement"
"what return-1 mean ?"
Last one first: return -1 means to return a negative value. Think about it:
If you pass 'a' you want it to return 0.
If you pass 'r' you want it to return 1.
If you pass 'x' what is it going to return? It can't return "nothing"!
Now the first: I assumed when you said "I can't use if statement" that you meant you don't know how to! I take it this is your tutor restricting your answer?
OK, the other form you describe can do it - you can "nest" them:
return (condition1 ? 0 : (condition2 ? 1 : 2));
So yes, that will work - I'll tidy it up for you:
return ((c >= 'a' && c <= 'i') ? 0 : ((c >= 'j' && c <= 'r') ? 1 : -1));
But... technically, that's still an if (well...two ifs :laugh:)
Have you considered a
switch
?
switch (c)
{
case 'a':
case 'b':
case 'c':
case 'd':
...
case 'h':
case 'i':
return 0;
case 'j':
case 'k':
...
case 'r':
return 1;
default:
return -1;
}
It's a lot more long-winded, but it's also a lot more readable and much more flexible. And it definitely doesn't use an if!