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

W4 5 Ch3 More Flow Control2

Uploaded by

mohammad3mhamdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

W4 5 Ch3 More Flow Control2

Uploaded by

mohammad3mhamdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.

Chapter 3
More Flow of Control

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Overview

3.3 C++ Loop Statements

3.4 Designing Loops

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 3
3.3
C++ Loop Statements

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


C++ Loop Statements

◼ A loop is a program construction that repeats a


statement or sequence of statements a number
of times
◼ The body of the loop is the statement(s) repeated

◼ Each repetition of the loop is an iteration

◼ Loop design questions:


◼ What should the loop body be?

◼ How many times should the body be iterated?

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 5
I. while loop
◼ When an action must be repeated, a loop is used
◼ C++ includes several ways to create loops
◼ We start with the while-loop
◼ Example: while (count_down > 0)
{
cout << "Hello ";
count_down -= 1;
}
◼ Output: Hello Hello Hello
when count_down starts at 3

Display 2.12

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 6
II. do-while loop
◼ A variation of the while loop
◼ A do-while loop is always executed at least once
◼ The body of the loop is first executed

◼ The boolean expression is checked after the body

has been executed


◼ Syntax: do Display 2.14
{ Display 2.15
statements to repeat;

} while (boolean_expression);

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 7
Increment/Decrement

◼ ++ increment operator
◼ Adds 1 to the value of a variable
x ++;
is equivalent to x = x + 1;
◼ -- decrement operator
◼ Subtracts 1 from the value of a variable
x --;
is equivalent to x = x – 1;

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 8
while and do-while Difference
◼ An important difference between while and
do-while loops:
◼ A while loop checks the Boolean expression at the

beginning of the loop


◼ A while loop might never be executed!
◼ A do-while loop checks the Boolean expression at
the end of the loop
◼ A do-while loop is always executed at least once
◼ Review while and do-while syntax in
Display 3.9

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 9
Sample Program
◼ Bank charge card balance of $50 (what you spent)
◼ 2% per month interest (penalty for not paying)
◼ Q: How many months to accumulate a debt of $100, if
starting with an initial balance of $50 owed?
◼ After 1 month: $50 + 2% of $50 = $51
◼ After 2 months: $51 + 2% of $51 = $52.02
◼ After 3 months: $52.02 + 2% of $52.02 …

Display 2.16
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 10
Infinite Loops
◼ Loops that never stop are infinite loops (problem due to
some error!)
◼ The loop body should contain a line that will eventually
cause the boolean expression to become false and,
hence, exit the loop
◼ Example: Print the odd numbers less than 12
x = 1;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
◼ Must use this comparison instead: while ( x < 12)
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 11
The Increment Operator

◼ We have used the increment operator in statements such


as:
number++;
to increase the value of number by one
◼ The increment operator can also be used in expressions:
int number = 2;
int value_produced = 2 * (number++);
◼ (number++) first returns the value of number (2) to

be multiplied by 2, then increments number to three!!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 12
number++ vs ++number

◼ (number++) returns the current value of number,


then increments number
◼ An expression using (number++) will use

the value of number BEFORE it is incremented


◼ (++number) increments number first and returns
the new value of number
◼ An expression using (++number) will use

the value of number AFTER it is incremented


◼ Number has the same value after either version!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 13
++ Comparisons
◼ int number = 2;
int value_produced = 2 * (number++);
cout << value_produced << " " << number;

displays 4 3
◼ int number = 2;
int value_produced = 2* (++number);
cout << value_produced << " " number;

displays 6 3
Display 3.10
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 14
III. The for-Statement

◼ A for-Statement (for-loop) is another loop


mechanism in C++
◼ Designed for common tasks such as adding

numbers in a given range


◼ Is sometimes more convenient to use than a

while loop (when the number of iterations is


known beforehand)
◼ Does not do anything a while loop cannot do

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 15
for/while Loop Comparison

◼ sum = 0;
n = 1;
while(n <= 10) // add the numbers 1 - 10
{
sum = sum + n;
n++;
}

◼ sum = 0;
for (n = 1; n <= 10; n++) //add the numbers 1 - 10
sum = sum + n;

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 16
For Loop Dissection

◼ The for loop uses the same components as the


while loop in a more compact form
◼ for (n = 1; n <= 10; n++)

Initialization Action Update Action

Boolean Expression

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 17
for Loop Alternative

◼ A for loop can also include a variable declaration


in the initialization action
◼ for (int n = 1; n < = 10; n++)

This line means


◼ Create a variable, n, of type int and initialize it with 1
◼ Continue to iterate the body as long as n <= 10
◼ Increment n by one after each iteration
◼ For-loop syntax and while loop comparison
are found in

Display 3.11

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 18
for-loop Details

◼ Initialization and update actions of for-loops


often contain more complex expressions
◼ Here are some samples

for (n = 1; n < = 10; n = n + 2)

for(n = 0 ; n > -100 ; n = n -7)


for(double x = pow(y,3.0); x > 2.0; x = sqrt(x) )
Display 3.13
◼ The for loop body can be: i) single statement or
ii) multiple statements enclosed by braces
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 19
The for-loop Body
◼ The body of a for-loop can be
◼ A single statement (no braces)
◼ A compound statement enclosed in braces

◼ Example:
for(int number = 100; number >= 0; number--)
{
// loop body statements
}
◼ Display 3.13 shows the syntax for a for-loop
with a multi-statement body

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 20
The Empty Statement
◼ A semicolon creates a C++ statement
◼ Placing a semicolon after x++ creates the statement

x++;
◼ Placing a semicolon after nothing creates an

empty statement that compiles but does nothing

cout << "Hello" << endl;


;
cout << "Good Bye"<< endl;

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 21
Extra Semicolon
◼ Pitfall: Placing a semicolon after the parentheses of a
for loop creates an empty statement as the
body of the loop
◼ Example: for(int count = 1; count <= 10; count++);
cout << "Hello\n";

prints one "Hello", but not as part of the loop!


◼ The empty statement is the body of the loop
◼ cout << "Hello\n"; is not part of the loop body!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 22
Which Loop To Use?

◼ Choose the type of loop late in the design process


◼ First design the loop using pseudocode

◼ Translate the pseudocode into C++

◼ The translation generally makes the choice of an

appropriate Loop clear

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 23
Choosing a for-loop

◼ for-loops are typically selected when doing


numeric calculations
◼ When there is a predetermined number of iterations
◼ When using a variable that changes by equal amount
each time the loop iterates

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 24
Choosing a while-loop

◼ A while-loop is typically used:


◼ When a for-loop is not appropriate (e.g. number

of loop iterations is unknown beforehand)

◼ When there are circumstances for which the


loop body should not be executed at all

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 25
Choosing a do-while Loop

◼ A do-while-loop is typically used:


◼ When a for-loop is not appropriate (e.g. number

of loop iterations is unknown beforehand)

◼ When the loop body must be executed at least


once

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 26
The break-Statement

◼ Often times, you need to exit a loop before it ends


◼ If the loop checks for invalid input that would
ruin a calculation, it is often best to end the
loop
◼ The break-statement can be used to exit a loop
before normal termination (abort it!)
◼ Be careful with nested loops! Using break only
exits the loop in which the break-statement
occurs
Display 3.14
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 27
Section 3.3 Conclusion
◼ Can you
◼ Determine the output of the following?

for(int count = 1; count < 5; count++)


cout << (2 * count) << " " ;

◼ Determine which type of loop is likely to be best


for
◼ Summing a series such as 1/2 + 1/3 + 1/4 + … + 1/10?
◼ Reading a list of exam scores for one student?
◼ Testing a function to see how it performs with different
values of its arguments

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 28
3.4
Designing Loops

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Designing Loops

◼ Designing a loop involves designing

◼ The body of the loop

◼ The initializing statements

◼ The conditions for ending the loop

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 30
for-loop for a sum

◼ Example: input a list of numbers and compute their


sum.

int sum = 0;
for(int count=1; count <= 100; count++)
{
cin >> next;
sum = sum + next;
}
◼ sum must be initialized to zero before the loop body!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 31
for-loop For a Product

◼ Example: Computing the product of numbers is very


similar to the sum example given earlier
int product = 1;
for(int count=1; count <= this_many; count++)
{
cin >> next;
product = product * next;
}
◼ product must be initialized prior to the loop body
◼ Notice that product is initialized to 1, not 0!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 32
Ending a Loop

◼ The are four common methods to terminate an input loop:


◼ List headed by size (for loop)
◼ When we can determine the size of the list beforehand
◼ Ask before iterating (while loop)
◼ Ask if the user wants to continue before each iteration
◼ List ended with a sentinel value (while loop)
◼ Using a particular value to signal the end of the list
◼ Running out of input (while loop)
◼ Using the eof function to indicate the end of a file

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 33
1. List Headed By Size
◼ The for-loops provide a natural implementation of the list
headed by size method of ending a loop
◼ Example: int items;
cout << "How many items in the list?";
cin >> items;
for(int count = 1; count <= items; count++)
{
int number;
cout << "Enter number " << count;
cin >> number;
cout << endl;
// statements to process the number
}

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 34
2. Ask Before Iterating
◼ A while loop is used here to implement the ask
before iterating method to end a loop
sum = 0;
cout << "Are there numbers in the list (Y/N)?";
char ans;
cin >> ans;

while (( ans == 'Y') || (ans == 'y'))


{
//statements to read and process the number
cout << "Are there more numbers(Y/N)? ";
cin >> ans;
}

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 35
3. List Ended With a Sentinel Value
◼ A while loop is typically used to end a loop using
the list ended with a sentinel value method

cout << "Enter a list of nonnegative integers.\n"


<< ”Enter a negative number to Exit.\n";
sum = 0;
cin >> number;
while (number > 0)
{
//statements to process the number
cin >> number;
}
◼ Notice that the sentinel value is read, but not processed

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 36
4. Running Out of Input
◼ The while loop is typically used to implement the
running out of input method of ending a loop

ifstream infile;
infile.open("data.dat");
while (! infile.eof( ) )
{
// read and process items from the file
// File I/O covered in Chapter 6
}
infile.close( );

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 37
Nested Loops

◼ The body of a loop may contain any kind of statement,


including another loop
◼ When loops are nested, all iterations of the inner loop

are executed for each iteration of the outer loop


◼ Give serious consideration to making the inner loop

a function call to make it easier to read your program


◼ Display 3.15 shows two versions of a program with nested
loops

Display 3.15
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 3- 38
Debugging Loops

◼ Common errors involving loops include

◼ Off-by-one errors in which the loop executes


one more or one less times

◼ Infinite loops usually result from a mistake


in the Boolean expression that controls
the loop

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 39
Fixing Off By One Errors
◼ Check your comparison:
should it be < or <=?

◼ Check that the initialization uses the


correct value (e.g., 0 vs. 1?)

◼ Does the loop handle the zero iterations


case?

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 40
Fixing Infinite Loops

◼ Check the direction of inequalities:


< or > ?

◼ Test for < or > rather than equality (==)


◼ Remember that doubles are really only

approximations

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 41
More Loop Debugging Tips …

◼ Be sure that the mistake is really in the loop


◼ Trace the variable to observe how the variable
changes
◼ Tracing a variable is tracking its value change during

execution
◼ Many systems include utilities/tools to help with this
◼ cout statements can be used to trace a value

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 42
Debugging Example
◼ The following code is supposed to conclude
with the variable product containing the product
of the numbers 2 through 5
int next = 2, product = 1;
while (next < 5)
{
next++;
product = product * next;
}

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 43
Tracing Variables
◼ Add temporary cout statements to trace variables

int next = 2, product = 1;


while (next < 5)
{
next++;
product = product * next;
cout << "next = " << next
<< "product = " << product
<< endl;
}

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 44
First Fix
◼ The cout statements added to the loop show us
that the loop never multiplied by 2
◼ Solve the problem by moving the statement next++

int next = 2, product = 1;


while (next < 5)
{
product = product * next;
next++;

cout << "next = " << next


<< "product = " << product
<< endl;
}

◼ But, there is still a problem!

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 45
Second Fix
◼ Re-testing the loop shows us that now the loop
never multiplies by 5
◼ The fix is to use <= instead of < in our comparison

int next = 2, product = 1;


while (next <= 5)
{
product = product * next;
next++;
}

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 46
Loop Testing Guidelines
◼ Every time a program is changed, it must be
retested
◼ Changing one part may require a change to another

◼ Every loop should at least be tested using input


to cause:
◼ Zero iterations of the loop body

◼ One iteration of the loop body

◼ One less than the maximum number of iterations

◼ The maximum number of iterations

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 47
Starting Over

◼ Sometimes it is more efficient to throw out a


buggy program and start all over
◼ The new program will be easier to read

◼ The new program is less likely to be as buggy

◼ You may develop a working program faster


than if you repair the bad code
◼ The lessons learned in the buggy code will help you
design a better program faster

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 48
Chapter 3.4 Conclusion

◼ Can you

◼ Describe how to trace a variable?

◼ List possible solutions to an off-by-one error?

◼ Determine the number of fence posts needed


for a 100 meter long fence?

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 49
Chapter 3 -- End

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 50
Display 2.12
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 51
Display 2.14 Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 52
Display 2.15
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 53
Display 3.9
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 54
Display 2.16
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 2- 55
Display 3.10
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 56
Display 3.11
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 57
Display 3.12 Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 58
Display 3.13 Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 59
Display 3.14
Back Next

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 60
Display 3.15
Back Next
//DISPLAY 3.15 Explicitly Nested Loops
//Determines the total number of green-necked vulture eggs
//counted by all conservationists in the conservation district. cout << "Enter the number of eggs in each nest.\n"
#include <iostream> << "Place a negative integer at the end of your list.\n";
using namespace std; subtotal = 0;
int next;
int main() cin >> next;
{ while (next >=0)
cout << "This program tallies conservationist reports\n" {
<< "on the green-necked vulture.\n" subtotal = subtotal + next;
<< "Each conservationist's report consists of\n" cin >> next;
<< "a list of numbers. Each number is the count of\n" }
<< "the eggs observed in one " cout << "Total egg count for conservationist "
<< "green-necked vulture nest.\n" << " number " << count << " is "
<< "This program then tallies " << subtotal << endl;
<< "the total number of eggs.\n"; grand_total = grand_total + subtotal;
}
int number_of_reports; cout << endl << "Total egg count for all reports = "
cout << "How many conservationist reports are there? "; << grand_total << endl;
cin >> number_of_reports;
return 0;
int grand_total = 0, subtotal, count; }
for (count = 1; count <= number_of_reports; count++)
{
cout << endl << "Enter the report of "
<< "conservationist number " << count << endl;

Copyright © 2018 Pearson Addison-Wesley. All rights reserved.


Slide 3- 61

You might also like