Reputation: 19
I have someone telling me that the logic in the if else-if below is not correct because I should have included an upper and lower limit in every else-if because when you enter a 6 more than one else-if is true; I thought that since the else-if breaks out when finding a true, that this was just as good. What do think?
int hoursOfSleep = 9;
if (hoursOfSleep >= 10 )
{
Console.WriteLine("Wow! That's a lot of sleep!");
}
else if (hoursOfSleep > 8 )
{
Console.WriteLine("You should be pretty rested.");
}
else if (hoursOfSleep > 5)
{
Console.WriteLine("That's not bad.");
}
else if (hoursOfSleep > 4)
{
Console.WriteLine("Bummer.");
}
else
{
Console.WriteLine("Oh man, get some sleep!");
}
Upvotes: 1
Views: 102
Reputation: 1137
You right.
The program will do either the task inside the if block if the test expression is true or the task inside the else if the test expression is false.
When using else if, it will do the same thing, check the expression in the if and continue to the else if it's false.
Only one hit is possible in if-else condition, if the test expression will remain false till the end then the last else will be execute.
Upvotes: 1