Next: Summary
Up: The if statement
Previous: The if statement
The following if
statement adds x
to a variable
sum
if x
is positive:
if (x > 0.0) sum += x;
The following if
statement also adds x
to sum
but
in addition it adds 1 to a count of positive numbers held in the variable
poscount
:
if (x >= 0.0) { sum += x; poscount++; }Note the use of the addition/assignment operator, and of the increment operator. Note how in the second example a compound statement has been used to carry out more than one operation if the condition is true. If this had been written as follows:
if (x >= 0.0) sum += x; poscount++;then if
x
was greater than zero the next statement would be
executed, that is x
would be added to sum
. However the
statement incrementing poscount
would then be treated as the
next statement in the program, and not as part of the if
statement. The effect of this would be that poscount
would be
incremented every time, whether x
was positive or negative.
The statements within a compound statement can be any C++ statements.
In particular, another if
statement could be included. For
example, to print a message if a quantity is negative, and a further
message if no overdraft has been arranged:
if ( account_balance < 0 ) { cout << "Your account is overdrawn. Balance " << account_balance << endl; if ( overdraft_limit == 0 ) cout << "You have exceeded your limit. << endl; }
In this case,
the same effect could have been achieved using two if
statements, and a more complex set of conditions:
if ( account_balance < 0 ) cout << "Your account is overdrawn. Balance " << account_balance << endl; if ( account_balance < 0 && overdraft_limit == 0 ) cout << "You have exceeded your limit. << endl;