Chapter 4: Basic Control Flow

Chapter Goals

The if Statement

The if Statement (Syntax 4.1 : if Statement)

Syntax 4.1 : if Statement

if (condition) statement
Example:
if (x >= 0) y = sqrt(x);
Purpose: Execute the statement if the condition is true.

The if Statement (Syntax 4.2 : Block Statement)

Syntax 4.2 : Block Statement

{ 
   statement1
   statement2
   ...
   statementn
}
Example:
{
   double length = sqrt(area);
   cout << area << "\n";
}
Purpose: Group several statements into a block that can be controlled by another statement.

The if Statement (area1.cpp)

The if/else Statement

The if/else Statement (Syntax 4.3 : if/else Statement)

Syntax 4.3 : if Statement

if (condition) statement1 else statement2
Example:
if (x >= 0) y = sqrt(x); else cout << "Bad input\n";
Purpose: Execute the first statement if the condition is true, the second statement if the condition is false.

The if/else Statement (Syntax 4.3 : if/else Statement)

Relational Operators

Relational Operators (comparing strings)

Input Validation

Input Validation (area3.cpp)

Simple Loops

Simple Loops (Syntax 4.4 : while Statement)

Syntax 4.4 : while Statement

while (condition) statement
Example:
while (x >= 10) x = sqrt(x);
Purpose: Execute the statement while the condition remains true.

Processing a Sequence of Inputs (Sentinels)

Processing a Sequence of Inputs (sentinel.cpp)

Processing a Sequence of Inputs (Causing the Stream to Fail)

Processing a Sequence of Inputs (maxtemp.cpp)

Using Boolean Variables