The
"if ... else if ... else" Statements
|
Let's look
at situations where your program requires more than two situations
as the result of a decision. |
cout<<"Enter
a value for a";
cin>>a;
cout<<"Enter a value for b";
cin>>b;
if(a= = b)
{
cout<<"They are equal!\n";
}
else if( a < b)
{
cout<<"The first number "
<< "is smaller.\n";
}
else
{
cout<<"The second number"
<< is smaller.\n";
} |
Notice that it was not necessary to check for
a>b in the third situation. The trichotomy principle
tells us that numbers are related in one of three ways (a
equals b, or a is less than b, or a is greater than b). In
order for the computer to get to the "else" condition in the
problem above, it must have answered NO to the first two decisions.
Consequently, there is only ONE possibility left and we do not waste the
computer's time checking it.
Return to Topic Menu
|
Computer Science Main Page |
MathBits.com
|
Terms of Use
|
Resource CD
|