Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

Chapter 3– Loops and Decisions

 Flow of Control - The order in which the computer executes statements


in a program.

 Control Structure - A statement used to alter the normal sequential flow


of control.
 There are four types of control structures used in C++:
1. Sequence - statements are executed one after the other.

 
2. Selection - one of two paths are executed based on a condition
(true/false expression).

3. Loop - one or more statements are executed while (or until) a


condition tests true.
4. Function call - execution of statements is suspended while
another function is executed. After the function returns, execution
continues immediately after the function call.

3.1 Decision and Branching Statements


3.1.1 Conditions and Logical Expressions
 Logical expressions evaluate to true or false.

 In C++, an integer expression that evaluates to 0 is false. Any other value


is true.
 A typedef statement is used to create C++ data types based on previously
defined types.

typedef int Boolean;


const Boolean TRUE = 1;
const Boolean FALSE = 0;

.
.
.

Boolean OK;

.
.
.

OK = TRUE;

.
.
.

OK = FALSE;

 Relational operators are used to compare two values:

= =    Equal
! =     Not equal
>       Greater than
>=     Greater than or equal
<       Less than
<=     Less than or equal

Examples:
x != y
x>y
y == 0
ch >= 'A'
x<y-z
 

 Logical operators consist of && (and), ||(or) and ! (not).

x y x && y x || y !x
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

Examples:

finalScore > 90 && midtermScore > 70


midtermGrade == 'A' || finalGrade == 'A'
!(hours > 40)is equivalent to hours <= 40

 Short-circuit evaluation. Evaluation of logical expressions stops as soon


as the result can be determined.

c <= d || e == f

if the first term is true, then the second term is not


evaluated.

 Precedence of Operators:

!                                            Highest precedence


*  /   %  
+  -
<  <=  >  >=
== !=
&&
||
=                                             Lowest precedence
 

Examples:

dataInvalid = inputVal == 0;
dataInvalid = (inputVal == 0);
OK = x * 5 < y + 6;
done = !OK && x < y;
 Relational operators and floating point types. Consider the following:

float oneThird = 1.0 / 3.0;


float one = oneThird + oneThird + oneThird;
cout << one << endl;
 

outputs

0.9999999

instead of 1.0. Why? Because 1.0 / 3.0 is not exactly one


third.

3.1.2 The If Statement


 The if statement is used to select between two paths in a C++ program.

 Syntax template

Example:

if (hours <= 40.0)

pay = rate * hours;

else

pay = rate * (40.0 + (hours - 40.0) * 1.5);

 A Compound Statement consists of a Block of simple statements


enclosed in braces { and }.

Example:
if (n >= 2)
{

alpha = 5;
beta = 15;

}
else
{

alpha = 23;
beta = 199;

  An alternate form of the if statement omits the else clause.

Example:
if (n >= 2)
{

alpha = 5;
beta = 15;

}
 

 A common mistake can occur when the == (equality) operator is confused


with the = (assignment) operator.

Example:
cin >> n;
if (n = 3)
cout << "n equals 3";
else
cout << "n doesn't equal 3";
 
What actually happens in this example?
 
In the if statement, n is assigned the value 3. The assignment
operator also results in a value (3) which is then tested for
true/false. Since 3 is not 0, the result is true, and the message
n equals 3
is output.

To avoid such problems, you can write any test that includes a
constant as follows:
 
cin >> n;
if (3 == n)

cout << "n equals 3";


else
cout << "n doesn't equal 3";

3.1.3 Nested If Statements


 There are no restrictions on what the statements in an if statement can be.
For example an if statement can contain another if statement.

if (x < 0)

if (y != 4)

z = y * x;

else

z = y / x;

else

if (y > 4)

z = y + x;

else

z = y - x;

 Consider the following code:

if (day == 1)

cout << "Sunday";

if (day == 2)

cout << "Monday";


if (day == 3)

cout << "Tuesday";

if (day == 4)

cout << "Wednesday";

if (day == 5)

cout << "Thursday";

if (day == 6)

cout << "Friday";

 if (day == 7)

cout << "Saturday";


 

It could be written more efficiently as:

if (day == 1)

cout << "Sunday";

else

if (day == 2)

cout << "Monday";

else

if (day == 3)

cout << "Tuesday";

else

if (day == 4)

cout << "Wednesday";

else

if (day == 5)
cout << "Thursday";

else

if (day == 6)

cout << "Friday";

 else

if (day == 7)

cout << "Saturday";

Eventhough the previous example conforms to the style guidelines for if


statements, it isn't very easy to read. The following alternative style is often used
for a compound if like this:

if (day == 1)

cout << "Sunday";

else if (day == 2)

cout << "Monday";

else if (day == 3)

cout << "Tuesday";

else if (day == 4)

cout << "Wednesday";

else if (day == 5)

cout << "Thursday";

else if (day == 6)

cout << "Friday";

else if (day == 7)

cout << "Saturday";

Remember that the layout of the program doesn't matter to


the compiler:
if (temp > 32)

if (temp <= 40)

cout << "Freeze Watch";

else

cout << "Freeze Warning";

The above code won't have the desired effect. It is


equivalent to:

if (temp > 32)

if (temp <= 40)

cout << "Freeze Watch";

else

cout << "Freeze Warning";

There are two ways to correct the problem. The following


solution uses what is known as the null else which is the
word else followed by a semicolon. It means to do nothing.

if (temp > 32)

if (temp <= 40)

cout << "Freeze Watch";

else;

else

cout << "Freeze Warning";


 

The sceond solution uses braces to delimit the embedded if


statement.  

if (temp > 32)


{

if (temp <= 40)

cout << "Freeze Watch";


}
else

cout << "Freeze Warning";

3.1.4 The Switch Statement


 Nested if statements can be used to select from one of several paths in a
program but the logic is sometimes difficult to follow:

if (grade = 'A')

gradePt = 4.0;

else if (grade = 'B')

gradePt = 3.0;

else if (grade = 'C')

gradePt = 2.0;

else if (grade = 'D')

gradePt = 1.0;

else if (grade = 'F')

gradePt = 0.0;

else

cout << "Invalid grade";


 

 The C++ switch statement provides a control structure for this type of
situation:

switch (grade)
{

case 'A' :

gradePt = 4.0; break;

case 'B' :

gradePt = 3.0; break;


case 'C' :

gradePt = 2.0; break;

case 'D :

gradePt = 1.0; break;

case 'F' :

gradePt = 0.0; break;

default :

cout << "Invalid grade";

switch syntax diagram:

 The switch expression is an integral expression that is used to select one


of the cases in the switch statement.

 If the value of the switch expression does not match any of the case
constants, control is transfered to the default case. If there is no default
case, control is passed to the statement following the brace at the end of
the switch statement.
3.2 Loops
3.2.1 The While Statement
 A Loop is a control structure that causes a sequence of statements to be
executed repeatedly.
 The While Statement tests a condition and repeats a block of one or more
statments as long as the condidition is true.
 While statement syntax diagram:

  Examples:
while (inputVal != 25)

cin >> inputVal;


 
 

x = 0;
while (x < 10)
{

cout << x << endl;


x++;

}
 

 While loop flow chart

 
 Phases of While Loop Execution
o Initialization occurs prior to the while statement.
o Loop entry occurs the moment that the flow of control reaches the first
statement inside the loop body.
o Each time the body of the loop is executed, a pass is made through the
loop. This pass is called an iteration.
o Before each iteration, the loop test is made at the beginning of the
loop.
o When the last iteration is complete and flow of control has passed to
the first statement after the loop, the program has exited the loop.
o The condition that causes the loop to exit is called the exit condition.

Count-Controlled Loops

 A count-controlled loop executes a specified number of times.


 Examples:
// Loop 10 times (1, 2, ... 10)
loopCount = 1;
while (loopCount <= 10)
{

.
.
.

loopCount++;

}
// Loop 10 times (0, 1, ... 9)
loopCount = 0;
while (loopCount < 10)
{

.
.
.

loopCount++;

// Loop 10 times (10, 9, ... 1)


loopCount = 10;
while (loopCount >= 1)
{

.
.
.

loopCount--;

Event-Controlled Loops

 An event-controlled loop is a loop that terminates when something


happens inside the loop body that signals that the loop should be exited.
 A sentinel is a special data value that is used to signal that there are no
more data values to be input.
 A sentinel-controlled loop reads in and processes lists of data. Each time
the loop body is executed, a new piece of data is read. If the data is not
the sentinel, the data is processed. If the sentinel is read, the loop is
terminated.

 Examples:

// Example 1. data variable initialized


//            to non-sentinel value.
int data = 0;
long sum = 0;
while (data != -1)    // -1 is sentinel
{

cin >> data;


if (data != -1)

sum += data;

// Example 2. Priming read.


int data;
long sum = 0;

cin >> data;


while (data != -1)    // -1 is sentinel
{

sum += data;
cin >> data;

3.2.2 Do-While Statement

 The while loop that we have been using tests its condition at the beginning of the
loop:

 
 There are some applications where a loop that tests its condition at the
bottom of the loop is better. The do ... while statement provides such a
loop:
 The Statement in the do ... while can be a single statement or a block of
statements enclosed in braces. The statement will always be executed at
least once:

 
 Examples:

While Solution do While Solution


  
dataFile >> inChar;  do 
while (inChar != '.')    dataFile >> inChar; 
  dataFile >> inChar;  while (inChar != '.');
 
  
cout << "Enter age: "; 
do 
cin >> age; 

while (age < 0) 
  cout << "Enter age: "; 

  cin >> age; 
  cout << "Age is negative"; 
  if (age < 0) 
  cout << "Enter age: "; 
   cout << "Age is negative"; 
  cin >> age; 
} while (age < 0);

 

 
3.2.3 For Statement
 A lot of loops are count controlled loops. The for statement makes it easy
to build such loops:

 
 The for loop tests at the bottom of the loop just as the while loop does:

 
 Examples:  

for (count = 1; count <= n; count++)


    cout << count << endl;

is equivalent to:

count = 1;
while (count <= n)
{
cout << count << endl;
count++;

}
 

The following for loops execute the same number of times:

for (count = 1; count <= 50; count++)

cout << count;


 

for (count = 50; count >= 1; count--)

cout << count;

 Loops can be nested to any depth:

for (count = 0; count < 10; count++)


{
for (digit = 0; digit <= count; digit++)
cout << digit;
cout << endl;
}

prints the following output:

0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
 

  Any of the components of the for statement may be null:

   for ( ; inVal != 999; )

cin >> inVal;


 
is equivalent to:
 

while (inVal != 999)

cin >> inVal;

and

 for ( ; ; ; )
{

cin >> inVal;


if (inVal < 0)

break;

is equivalent to:
 

while (1)
{

cin >> inVal;


if (inVal < 0)

break;

3.3 break and continue Statements

 The break statement is used to exit from the innermost switch or loop
control structure.

loopCount = 1;
while (TRUE)
{

cin >> num1;


if ( !cin || num1 >= 100)

break;

cin >> num2;


if ( !cin || num2 <= 50)
break;

cout << sqrt(float(num1 + num2))


     << endl;
loopCount++;
if (loopCount > 10)

break;

}
 

 When the break statement is executed, control is transfered to the


statement following the switch or loop.

 The continue statement can be used with a loop to cause it to suspend


execution of the current iteration and continue with the next iteration.

// Output first 500 non-negative values


dataCount = 0;
while (dataFile && dataCount < 500)
{

dataFile >> inputVal;


if (!dataFile)

break;

if (inputVal < 0)

continue;

cout << inputVal;

dataCount++;

}
 

Note that when a negative value is read, the cout statement and the
dataCount++; statement are skipped, but the loop continues by reading
another value.

You might also like