Title: More About Loops Program Design and Testing
1Chapter 8
More About Loops Program Design and Testing
2Outline
- Guidelines for constructing a loop structure
- Exit a loop using the break statement
- Nested loop
- Designing and writing programs
- Chapter 7
- Paid attention to fixed-step and data input loops
- Chapter 8
- Loops that exit on completion of the task
- Dont know ahead of time how many times to loop
- Have to recognize exit criterion when it comes up
- Middle-exit loops using break statement
3Steps in Designing the Loop
- If 500 is invested at a rate of 4.5
compounded annually, after how many years will
the balance first exceed 1,000? (Page 178) - What variables are needed?
- Year counter (int)
- Balance in the account (double)
- What must happen before the loop?
- Initialize Year to 0
- Initialize Balance to 500.0
- What happens after the loop?
- Print number of years
- Print balance
4Example (contd)
- What is the loop test?
- Is Balance lt 1000.00 or gt 1000.00?
- Any reason to use a bottom-exit loop (do-while)?
No. - Test is while (Balance lt 1000.0)
- What is in the body of the loop?
- Increase Balance by (Balance 0.045)
- Increase Year by 1
- Pseudocode
- Initialize Year to 0 and Balance to 500.0
- while (Balance lt 1000.0)
-
- Increase Balance by (Balance 0.045)
- Increase Year by 1
-
- Print Year Balance
5Coding the Loop
- int main ()
-
- const double RATE 0.045 // 4.5
- double Balance 500.0
- int Year 0
- while (Balance lt 1000.0)
-
- Balance Balance RATE Balance
- Year
- cout ltlt Year ltlt " " ltlt Balance ltlt endl //
DEBUG -
- cout ltlt "500 invested at " ltlt RATE
- ltlt " takes " ltlt Year ltlt " years to grow
to " - ltlt Balance ltlt " (over 1,000)." ltlt endl
- return 0
6Testing the Loop
- How do you know whether its right?
- Do you have a compound interest calculator?
- If you have Excel, you do
- Heres where the debug code comes in handy
- Tells you where program got to if it doesnt come
back - Tells you the steps it took so you can validate
its operation - What Can Go Wrong?
- What if you had used lt rather than lt as a
test? - What if you had said Balance RATE Balance?
- What if you had initialized Year to 1, instead of
0? (Off-by-One errors) - How difficult would it be to discover this one?
7What to check?
- Initialization
- Check the initial value of loop control or other
key variables - Order
- Check where the loop control variables be updated
- Relational Operator
- Check the relational operator in the loop exit
(condition) test - lt or lt
- or !
- First and Last Execution of Loop Body
8Multiple Reasons for a Loop Exit
- When there are two or more possible reasons for
exiting a loop, a compound condition is used in
the loop exit test. - Use an if else statement after the loop to
determine which condition caused the exit
do cout ltlt "The residency status should be
R or N. \n" cout ltlt "Please enter the
residency status (R or N) " cin gtgt
chResStatus while (chResStatus ! 'R'
chResStatus ! 'N') if (chResStatus R)
cout ltlt The student is resident. ltlt
endl else cout ltlt The student is
nonresident. ltlt endl
9The Middle-Exit Loop
- Uses the break Statement to exits innermost loop
construct - int Number, Count 0
- int Sum 0
- while (true)
-
- cout ltlt "Enter a number "
- cin gtgt Number
- if (Number lt 0)
- break
- Sum Number
- Count
-
- cout ltlt Sum is ltlt Sum ltlt endl
- cout ltlt Count is ltlt Count ltlt endl
- Another Example capital2.cpp
10Nested Loops - Loop Within a Loop
11Nested Loops - Loop Within a Loop
- int Number, Sum
- while (true)
-
- cout ltlt "Enter a number "
- cin gtgt Number
- if (Number lt 0)
- break
- Sum 0
- for (int i0 iltNumber i)
-
- Sum i
- if (Sum gt 10)
- break
-
- cout ltlt Sum is ltlt Sum ltlt endl
12Nested Loops - Loop Within a Loop
- int row, col
- for (row1 rowlt4 row))
-
- cout ltlt Row ltlt row ltlt
- for (col1 colltrow col)
-
- cout ltlt
-
- cout ltlt endl
-
Row 1 Row 2 Row 3 Row 4
13Nested Loops - Loop Within a Loop
14Nested Loops - Loop Within a Loop
include ltcctypegt
15Designing WritingPrograms
16Four Steps in Program Development
- Requirements analysis
- Understand the requirements (what must be done)
- Program design
- Figure out the logical flow of the program (how
to do it) - Program coding
- Write the code for the program (do it)
- Program testing
- Figure out the best test cases for it run it on
those cases (make sure its being done right)
17Example Assignment 3
- The delivery charge for the first pound (i.e., 16
ounces) is 3.00 and 0.50 is added to the charge
for each additional 4 ounces. For example, - a package weighing more that 16 ounces but at
most 20 ounces costs 3.50 to deliver - a package weighing more than 20 but at most 24
ounces costs 4.00 to deliver etc. - An optional delivery confirmation at 0.45 per
package. - Input the weight and delivery confirmation
choice, compute and output the delivery charge.
18The Requirement Analysis
- Stay at the same level as the words of the
problem statement until you understand what its
asking for - Inputs
- weight
- delivery confirmation choice
- compute the delivery charge
- need to handle the delivery confirmation choice
- use calcCharge function
- output the delivery charge
- use dispCharge function
19Program design and coding
Some things well always haveCompiler
directivesmain Function Declarations
initializations Main code for the function (in
this case, compute delivery charge) Other things
we may haveDeclarations outside
functions (e.g., constants)In main function
Outputs (at end of main body or in middle of
main body)Additional functions Perform needed
sub-tasks
Complier directives
Global constants declarations
Function declarations
main
Variable declarationsand Initializations
Input
Compute by function call
Output by function call
Function definitions
20Components before main
- Compiler directives
- include ltiostreamgt
- directives for the libraries well use
- using namespace std
- Namespaces used in very large programming
projects - For us, just put this line at the top of every
program - Optional global constants
- const double MIN_CHARGE 3.00
- Function Declarations
- double calcCharge(double dWeight, char
chConfirm)
21main Function
- Variable Declarations
- double dPackageWeight
- char chDeliveryConfirm
- double dTotalCharge
-
- Youll see what you need to declare as you
move through the design of the function - Add declarations as you realize or decide
that you need places to store things in the code
22main Function
- Initializations and Input
- For some variables, add initializations onto
the declarations - Things that start as 0 (integers) or "" (strings)
- For other variables, initialize explicitly in the
code - Later, when program has run for a while
- Example loop counter (Assignment 4)
- Values gotten from outside in this case,
get the weight and delivery confirmation choice
from the user - Prompt user for data (tell user what you want)
- Get data from user
- Check input data for correctness
23main Function Call other Functions
- // call calcCharge()
- get the total charge
- // call dispCharge()
- output the total charge
24Implement Functions
- double calcCharge()
- what parameters are needed to computer
totalcharge? - weight double? or int?
- delivery confirmation choice char
- how to compute the totalcharge?
- two cases delivery confirmation / or not?
- math function ceil(double x)
- return the total charge
- void dispCharge()
- parameter the totalcharge
- cout ltlt
25Testing a Program
- Overall Process
- Give your program inputs whose output you know
- Look at the outputs from those inputs are they
correct for the inputs you provided? - But theres more to it than that
- Most important deciding which inputs test
cases to give it - Test a wide range of input values
- Normal (correct) input values
- Erroneous (incorrect) input values
- Boundary conditions values
- And any cases youre not sure about
26Example Assignment 4
- In main function, input the number of employees
with input prompts. - LOOP 1 Ask the user to reinput the value if the
it is invalid, e.g., a negative number, until the
input value is valid. - LOOP 2 in main function
- (1) input the full name, hours worked, and base
pay rate for each employee - (2) calculate the gross wage for each employee by
calling the function CalcGrossWage - (3) calculate the net tax for each employee by
calling the function CalcNetTax - (4) calculate the net wage for each employee
- (5) output a table like the following based on
the information of each employee
27Top-down Design
- Think of your program from the top down (or from
the outside in) - If you need a loop, figure out what the loop as
a whole needs to do before you work on what goes
inside it - Write the skeleton for a loop as a whole first
- for ( )
-
-
-
- Then go back and fill in the blanks
28Controlling the loop
- What kind of controls are there in general?
- while? do-while? for?
- LOOP1
- controlled by the input of user,
- We do not know how many times the user have to
try - so we use
- LOOP2
- controlled by the number of employees, i.e., the
input we get from LOOP1, - We know how many times we should loop,
- so we use
29Contents of the Loop 2 (computation loop)
- For each employee
- Prompt user for the input record
- May want to put full prompt only once, above the
loop - Then use a minimal prompt each time user input is
requested - Get record from user
- Need an int variable for hours worked, a double
variable for base pay rate, and a string for the
full name - Be careful when inputting the full name
- can we use cin gtgt ?
- Any validity checks needed? Not for this problem
30Contents of the Loop 2 (computation loop)
- Two function calls
- // call the function CalcGrossWage to get gross
wage - // call the function CalcNetTax to get net tax
- // calculate the net wage for each employee
- // Output the results as the required format
31Contents of the Loop 2 what else?
- (a) the total gross for all employees, (b) the
total tax withheld from all employees, (c) the
average net pay, and (d) the name and gross wage
for the employee with the largest gross. - Initialize variables of total gross and total
tax - LOOP2
-
- // calculate the net wage for each employee
- // calculate (a) and (b)
- // find (d)
- // Output the results as the required format
-
- calculate (c)
32Using if to Handle Error Cases
- Situation
- Use an if test to discover whether theres been
a problem - If there has been, issue a message and get out
- If not, do a (sometimes big) hunk of code
- Question which side of the if block to
write first? - The code to handle the success case
- The code to handle the fail case
- Answer write the shorter piece of code first
- Whether its the success or fail case
- That way, both sides are right there under your
eyes as you look at the if statement - Keeps you from having to search down the program
page to find the other side