Next: Examples of if-else statements
Up: Introduction to C++ Programming
Previous: Exercises
A simple if
statement only allows selection of a statement
(simple or compound) when a condition holds. If there are
alternative statements, some which need to be executed when the
condition holds, and some which are to be executed when the condition
does not hold. This can be done with simple if
statements as
follows:
if (disc >= 0.0) cout << "Roots are real"; if (disc < 0.0 ) cout << "Roots are complex";This technique will work so long as the statements which are executed as a result of the first
if
statement do not alter the
conditions under which the second if
statement will be
executed. C++ provides a direct means of expressing this selection.
The if-else
statement specifies statements to be executed for
both possible logical values of the condition in an if
statement.
The following example of an if-else
statement writes out one
message if the variable disc
is positive and another message if
disc
is negative:
if (disc >= 0.0) cout << "Roots are real"; else cout << "Roots are complex";
The general form of the if-else
statement is:
if (
condition)
statementT
else
statementF
If the condition is true then statementT is executed, otherwise statementF is executed. Both statementF and statementT may be single statements or compound statements. Single statements must be terminated with a semi-colon.