0% found this document useful (0 votes)
27 views

Control Structures Revision

Uploaded by

mickyaszenebe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Control Structures Revision

Uploaded by

mickyaszenebe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Chapter 4: Making Decisions

Starting Out with C++


Early Objects
Seventh Edition

by Tony Gaddis, Judy Walters,


and Godfrey Muganda

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics
4.1 Relational Operators
4.2 The if Statement
4.3 The if/else Statement
4.4 The if/else if Statement
4.5 Menu-Driven Programs
4.6 Nested if Statements
4.7 Logical Operators
4.8 The Conditional Operator
4.9 The switch Statement
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-2
4.1 Relational Operators

• Used to compare numbers to determine


relative order
• Operators:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-3
Relational Expressions

• Relational expressions are Boolean


(i.e., evaluate to true or false)
• Examples:
12 > 5 is true
7 <= 5 is false
if x is 10, then
x == 10 is true,
x != 8 is true, and
x == 8 is false

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-4


Relational Expressions

• Can be assigned to a variable


bool result = (x <= y);
• Assigns 0 for false, 1 for true
• Do not confuse = (assignment) and ==
(equal to)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-5


4.2 The if Statement

• Allows statements to be conditionally


executed or skipped over

• Models the way we mentally evaluate


situations
“If it is cold outside,
wear a coat and wear a hat.”

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-6


Format of the if Statement
No
if (condition) ; goes here
{
statement1;
statement2; ; goes here

statementn;
}
The block inside the braces is called the body
of the if statement. If there is only 1 statement
in the body, the { } may be omitted.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-7
How the if Statement Works

• If (condition) is true, then the


statement(s) in the body are executed.

• If (condition) is false, then the


statement(s) are skipped.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-8


if Statement Flow of Control

condition

true false
1 or more
statements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-9


Example if Statements

if (score >= 60)


cout << "You passed.\n";

if (score >= 90)


{
grade = 'A';
cout << "Wonderful job!\n";
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-10


if Statement Notes

• Do not place ; after (condition)


• Don't forget the { } around a multi-statement
body
• Place each statement; on a separate
line after (condition), indented
• 0 is false; any other value is true

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-11


What is true and false?

• An expression whose value is 0 is


considered false.
• An expression whose value is non-zero is
considered true.
• An expression need not be a comparison –
it can be a single variable or a
mathematical expression.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-12


4.3 The if/else Statement

• Allows a choice between statements


depending on whether (condition) is true
or false
• Format: if (condition)
{
statement set 1;
}
else
{
statement set 2;
}
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-13
How the if/else Works

• If (condition) is true, statement


set 1 is executed and statement set 2
is skipped.

• If (condition) is false, statement


set 1 is skipped and statement set 2
is executed.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-14


if/else Flow of Control

true false
condition

statement statement
set 1 set 2

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-15


Example if/else Statements
if (score >= 60)
cout << "You passed.\n";
else
cout << "You did not pass.\n";

if (intRate > 0)
{ interest = loanAmt * intRate;
cout << interest;
}
else
cout << "You owe no interest.\n";
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-16
4.4 The if/else if Statement

• Chain of if statements that test in order


until one is found to be true
• Also models thought processes
“If it is raining, take an umbrella,
else, if it is windy, take a hat,
else, if it is sunny, take sunglasses.”

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-17


if/else if Format

if (condition 1)
{ statement set 1;
}
else if (condition 2)
{ statement set 2;
}

else if (condition n)
{ statement set n;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-18


Using a Trailing else

• Used with if/else if statement when all


of the conditions are false
• Provides a default statement or action
• Can be used to catch invalid values or
handle other exceptional situations

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-19


Example if/else if with Trailing else
if (age >= 21)
cout << "Adult";
else if (age >= 13)
cout << "Teen";
else if (age >= 2)
cout << "Child";
else
cout << "Baby";

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-20


4.5 Menu-Driven Program

• Menu: list of choices presented to the user


on the computer screen
• Menu-driven program: program execution
controlled by user selecting from a list of
actions
• Menu can be implemented using
if/else if statements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-21


Menu-driven Program Organization

• Display list of numbered or lettered choices


for actions.
• Input user’s selection of number or letter
• Test user selection in (condition)
– if a match, then execute code to carry out
desired action
– if not, then test with next (condition)

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-22


4.6 Nested if Statements
• An if statement that is part of the if or
else part of another if statement
• Can be used to evaluate > 1 data item or
condition
if (score < 100)
{
if (score > 90)
grade = 'A';
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-23


Notes on Coding Nested ifs

• An else matches the nearest if that does


not have an else
if (score < 100)
if (score > 90)
grade = 'A';
else ... // goes with second if,
// not first one
• Proper indentation aids comprehension
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-24
4.7 Logical Operators

Used to create relational expressions from


other relational expressions

Operators, Meaning, and Explanation


&& AND New relational expression is true if
both expressions are true
|| OR New relational expression is true if
either expression is true
Reverses the value of an expression;
! NOT true expression becomes false, false
expression becomes true
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-25
Logical Operator Examples

int x = 12, y = 5, z = -4;



(x > y) && (y > z) true

(x > y) && (z > y) false


(x <= z) || (y == z) false
(x <= z) || (y != z) true
!(x >= z) false

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-26


Logical Precedence

Highest !
&&
Lowest ||
Example:
(2 < 3) || (5 > 6) && (7 > 8)

is true because AND is evaluated before OR

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-27


More on Precedence

Highest arithmetic operators


relational operators
Lowest logical operators
Example:
8 < 2 + 7 || 5 == 6 is true

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-28


Checking Numeric Ranges with
Logical Operators
• Used to test if a value is within a range
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
• Can also test if a value lies outside a range
if (grade <= 0 || grade >= 100)
cout << "Invalid grade";
• Cannot use mathematical notation
if (0 <= grade <= 100) //Doesn’t
//work!

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-29


4.8 The Conditional Operator
• Can use to create short if/else
statements
• Format: expr ? expr : expr;

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-30


4.9 The switch Statement

• Used to select among statements from


several alternatives

• May sometimes be used instead of


if/else if statements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-31


switch Statement Format
switch (IntExpression)
{
case exp1: statement set 1;
case exp2: statement set 2;
...
case expn: statement set n;
default: statement set n+1;
}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-32


switch Statement Requirements

1) IntExpression must be a char or an


integer variable or an expression that
evaluates to an integer value
2) exp1 through expn must be constant
integer type expressions and must be
unique in the switch statement
3) default is optional but recommended

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-33


How the switch Statement Works
1) IntExpression is evaluated
2) The value of intExpression is compared
against exp1 through expn.
3) If IntExpression matches value expi, the
program branches to the statement(s) following
expi and continues to the end of the switch
4) If no matching value is found, the program
branches to the statement after default:

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-34


The break Statement

• Used to stop execution in the current block


• Also used to exit a switch statement
• Useful to execute a single case statement
without executing statements following it

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-35


Example switch Statement

• switch (gender)
•{
• case 'f': cout << "female";
• break;
• case 'm': cout << "male";
• break;
• default : cout << "invalid gender";
•}

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-36


Using switch with a Menu
switch statement is a natural choice for
menu-driven program
– display menu
– get user input
– use user input as IntExpression in switch
statement
– use menu choices as exp to test against in the
case statements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-37


Chapter 5: Looping

Starting Out with C++


Early Objects
Eighth Edition

by Tony Gaddis, Judy Walters,


and Godfrey Muganda

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics
5.1 Introduction to Loops: The while Loop
5.2 Using the while loop for Input Validation
5.3 The Increment and Decrement Operators
5.4 Counters
5.5 The do-while loop
5.6 The for loop
5.7 Deciding Which Loop to Use
5.8 Nested Loops
5.9 Breaking Out of a Loop
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-39
5.1 Introduction to Loops:
The while Loop

• Loop: part of program that may execute > 1


time (i.e., it repeats)
• while loop format:
while (condition)
{ statement(s); No ; here
}
• The {} can be omitted if there is only one
statement in the body of the loop

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-40
How the while Loop Works
while (condition)
{ statement(s);
}
condition is evaluated
– if it is true, the statement(s) are executed,
and then condition is evaluated again
– if it is false, the loop is exited

An iteration is an execution of the loop body


Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-41
while Loop Flow of Control

false
condition

true

statement(s)

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-42
while Loop Example
int val = 5;
while (val >= 0)
{ cout << val << " ";
val = val - 1;
}
• produces output:
5 4 3 2 1 0

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-43
while Loop is a Pretest Loop

• while is a pretest loop (condition is evaluated


before the loop executes)

• If the condition is initially false, the statement(s) in


the body of the loop are never executed

• If the condition is initially true, the statement(s) in


the body will continue to be executed until the
condition becomes false

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-44
Exiting the Loop

• The loop must contain code to allow


condition to eventually become false
so the loop can be exited
• Otherwise, you have an infinite loop (i.e., a
loop that does not stop)
• Example infinite loop:
x = 5;
while (x > 0) // infinite loop because
cout << x; // x is always > 0
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-45
Common Loop Errors
• Don’t put ; immediately after (condition)
• Don’t forget the { } :
int numEntries = 1;
while (numEntries <=3)
cout << "Still working … ";
numEntries++; // not in the loop body

• Don’t use = when you mean to use ==


while (numEntries = 3) // always true
{
cout << "Still working … ";
numEntries++;
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-46
while Loop Programming Style
• Loop body statements should be indented

• Align { and } with the loop header and place


them on lines by themselves

Note: The conventions above make the


program more understandable by someone
who is reading it. They have no effect on how
the program compiles or executes.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-47
5.2 Using the while Loop for Input
Validation
Loops are an appropriate structure for
validating user input data
1. Prompt for and read in the data.
2. Use a while loop to test if data is valid.
3. Enter the loop only if data is not valid.
4. Inside the loop, display error message and
prompt the user to re-enter the data.
5. The loop will not be exited until the user
enters valid data.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-48
Input Validation Loop Example

cout << "Enter a number (1-100) and"


<< " I will guess it. ";
cin >> number;
while (number < 1 || number > 100)
{ cout << "Number must be between 1 and 100."
<< " Re-enter your number. ";
cin >> number;
}
// Code to use the valid number goes here.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-49
5.3 The Increment and Decrement
Operators
• Increment – increase value in variable
++ adds one to a variable
val++; is the same as val = val + 1;

• Decrement – reduce value in variable


-- subtracts one from a variable
val--; is the same as val = val – 1;

• can be used in prefix mode (before) or


postfix mode (after) a variable
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-50
Prefix Mode

• ++val and --val increment or decrement


the variable, then return the new value of
the variable.
• It is this returned new value of the variable
that is used in any other operations within
the same statement

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-51
Prefix Mode Example
int x = 1, y = 1;

x = ++y; // y is incremented to 2
// Then 2 is assigned to x
cout << x
<< " " << y; // Displays 2 2

x = --y; // y is decremented to 1
// Then 1 is assigned to x
cout << x
<< " " << y; // Displays 1 1

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-52
Postfix Mode

• val++ and val-- return the old value of


the variable, then increment or decrement
the variable
• It is this returned old value of the variable
that is used in any other operations within
the same statement

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-53
Postfix Mode Example
int x = 1, y = 1;

x = y++; // y++ returns a 1


// The 1 is assigned to x
// and y is incremented to 2
cout << x
<< " " << y; // Displays 1 2

x = y--; // y-- returns a 2


// The 2 is assigned to x
// and y is decremented to 1
cout << x
<< " " << y; // Displays 2 1

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-54
Increment & Decrement Notes

• Can be used in arithmetic expressions


result = num1++ + --num2;
• Must be applied to something that has a
location in memory. Cannot have
result = (num1 + num2)++; // Illegal
• Can be used in relational expressions
if (++num > limit)
• Pre- and post-operations will cause different
comparisons
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-55
5.4 Counters
• Counter: variable that is incremented or
decremented each time a loop repeats
• Can be used to control execution of the
loop (loop control variable)
• Must be initialized before entering loop
• May be incremented/decremented either
inside the loop or in the loop test

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-56
Letting the User Control the Loop

• Program can be written so that user input


determines loop repetition
• Can be used when program processes a list
of items, and user knows the number of
items
• User is prompted before loop. Their input is
used to control number of repetitions

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-57
User Controls the Loop Example
int num, limit;
cout << "Table of squares\n";
cout << "How high to go? ";
cin >> limit;
cout << "\n\nnumber square\n";
num = 1;
while (num <= limit)
{ cout << setw(5) << num << setw(6)
<< num*num << endl;
num++;
}
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-58
5.5 The do-while Loop

• do-while: a post test loop (condition


is evaluated after the loop executes)
• Format:
do
{ 1 or more statements;
} while (condition);
Notice the
required ;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-59
do-while Flow of Control

statement(s)

true
condition

false

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-60
do-while Loop Notes

• Loop always executes at least once


• Execution continues as long as
condition is true; the loop is exited
when condition becomes false
• { } are required, even if the body contains
a single statement
• ; after (condition) is also required

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-61
do-while and Menu-Driven Programs

• do-while can be used in a menu-driven


program to bring the user back to the
menu to make another choice
• To simplify the processing of user input,
use the toupper (‘to upper’) or tolower
(to lower’) function

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-62
Menu-Driven Program Example

do {
// code to display menu
// and perform actions
cout << "Another choice? (Y/N) ";
} while (choice =='Y'||choice =='y');

The condition could be written as


(toupper(choice) == 'Y');
or as
(tolower(choice) == 'y');

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-63
5.6 The for Loop

• Pretest loop that executes zero or more times


• Useful for counter-controlled loop
Required ;
• Format:
for( initialization; test; update )
{ 1 or more statements;
}
No ; goes
here

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-64
for Loop Mechanics

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-65
for Loop Flow of Control

initialization
code

update
code
false
test

true

statement(s)

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-66
for Loop Example

int sum = 0, num;


for (num = 1; num <= 10; num++)
sum += num;
cout << "Sum of numbers 1 – 10 is "
<< sum << endl;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-67
for Loop Notes

• If test is false the first time it is evaluated,


the body of the loop will not be executed
• The update expression can increment or
decrement by any amount
• Variables used in the initialization section
should not be modified in the body of the
loop

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-68
for Loop Modifications

• Can define variables in initialization code


– Their scope is the for loop
• Initialization and update code can contain
more than one statement
– Separate the statements with commas
• Example:
for (int sum = 0, num = 1; num <= 10; num++)
sum += num;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-69
More for Loop Modifications
(These are NOT Recommended)
• Can omit initialization if already done
int sum = 0, num = 1;
for (; num <= 10; num++)
sum += num;
• Can omit update if done in loop
for (sum = 0, num = 1; num <= 10;)
sum += num++;
• Can omit test – may cause an infinite loop
for (sum = 0, num = 1; ; num++)
sum += num;
• Can omit loop body if all work is done in header

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-70
5.7 Deciding Which Loop to Use

• while: pretest loop (loop body may not


be executed at all)
• do-while: post test loop (loop body will
always be executed at least once)
• for: pretest loop (loop body may not be
executed at all); has initialization and
update code; is useful with counters or if
precise number of repetitions is known
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-71
5.8 Nested Loops

• A nested loop is a loop inside the body of


another loop
• Example:
outer loop
for (row = 1; row <= 3; row++)
{
inner loop
for (col = 1; col <= 3; col++)
{
cout << row * col << endl;
}
}
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-72
Notes on Nested Loops
• Inner loop goes through all its repetitions
for each repetition of outer loop
• Inner loop repetitions complete sooner than
outer loop
• Total number of repetitions for inner loop is
product of number of repetitions of the two
loops. In previous example, inner loop
repeats 9 times

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-73
5.9 Breaking Out of a Loop

• Can use break to terminate execution of


a loop
• Use sparingly if at all – makes code harder
to understand
• When used in an inner loop, terminates
that loop only and returns to the outer loop

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-74
The continue Statement

• Can use continue to go to end of loop


and prepare for next repetition
– while and do-while loops go to test and
repeat the loop if test condition is true
– for loop goes to update step, then tests, and
repeats loop if test condition is true
• Use sparingly – like break, can make
program logic hard to follow

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-75

You might also like