Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 85

4


6: using std::cout;
7: using std::cin;
8:
9: int firstNumber, secondNumber;
10: cout << “Please enter a big number: “;
11: cin >> firstNumber;
12: cout << “\nPlease enter a smaller number: “;
13: cin >> secondNumber;
14: if (firstNumber > secondNumber)
15: cout << “\nThanks!\n”;
16: else
17: cout << “\nOops. The first number is not bigger!”;
18:
19: return 0;
20: }

Please enter a big number: 10

Please enter a smaller number: 12
Oops. The first number is not bigger!
The ifstatement on line 14 is evaluated. If the condition is true, the statement on
line 15 is run and then program flow goes to line 18 (after the elsestatement). If
the condition on line 14 evaluates to false, control goes to the elseclause and so the
statement on line 17 is run. If the elseclause on line 16 was removed, the statement on
line 17 would run regardless of whether the ifstatement was true.
Remember, the ifstatement ends after line 15. If the elsewas not there, line 17 would
just be the next line in the program. You should also note that either or both of the ifand
the elsestatements could be replaced with a block of code in braces.

OUTPUT


LISTING4.5 continued


ANALYSIS

The ifStatement
The syntax for the ifstatement is as follows:
Form 1
if (expression)
statement;
next_statement;
If the expressionis evaluated as true, the statementis executed and the program contin-
ues with the next_statement. If the expressionis not true, the statementis ignored and
the program jumps to the next_statement.
Remember that the statement can be a single statement ending with a semicolon or a
block enclosed in braces.
Free download pdf