This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Intro To C++ - Class 12 - For, do … While
1. An Introduction To Software
Development Using C++
Class #12:
For, do … While
2. Volkswagen's Appalling
Clean Diesel Scandal
• What did they do?
– Since 2009, we now know, Volkswagen had been inserting intricate code in its vehicle
software that tracked steering and pedal movements.
– When those movements suggested that the car was being tested for nitrogen-oxide
emissions in a lab, the car automatically turned its pollution controls on.
– The rest of the time, the pollution controls switched off.
• Who discovered that bad things were going on?
– The International Council on Clean Transportation, wanted to investigate why there was
such a discrepancy between laboratory tests and real-road performance for several of
VW's diesel cars in Europe. So they worked with researchers at West Virginia University,
who stuck a probe up the exhaust pipe of VW's clean diesel cars and drove them from
San Diego to Seattle.
– What the researchers found was shocking. On the road, VW's Jetta was emitting 15 to
35 times as much nitrogen oxide as the allowable limit. The VW Passat was emitting 5 to
20 times as much. These cars were emitting much more pollution than they had in the
labs.
3. How Did VW Cheat?
• When carmakers test their vehicles against EPA standards, they place a car
on rollers and then perform a series of specific maneuvers prescribed by
federal regulations. Among the most common tests for passenger cars is
the Urban Dynamometer Driving Schedule (UDDS), which simulates 7.5
miles of urban driving.
• The detailed requirements for each test gave
Volkswagen the advance knowledge it
needed to teach its cars when to behave
more cleanly. By measuring how long the
engine was running, the vehicle’s speeds, and even seemingly esoteric
factors, such as the position of the steering wheel and barometric
pressure, Volkswagen vehicles could understand they were being tested
and so adjusted their engine performance to pass the tests
• Knowing when to switch to the EPA-favorable cycle is the trick
4. Essentials of
Counter-Controlled Repetition
Counter-controlled repetition requires:
1. the name of a control variable (or loop counter)
2. the initial value of the control variable
3. the loop-continuation condition that tests for the final value of the control variable
(i.e., whether looping should continue)
4. the increment (or decrement) by which the control variable is modified each time
through the loop.
Image Credit: tullyphotography.wikispaces.com
5. Program To Print the
Numbers From 1 to 10
1// Title: Program to print the numbers from 1-10
2 // Counter-controlled repetition.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 int counter = 1; // declare and initialize control variabl
9
10 while ( counter <= 1) // loop-continuation condition
11 {
12 cout << counter << " ";
13 ++counter; // increment control variable by 1
14 } // end while
15
16 cout << endl; // output a newline
17 } // end main
Image Credit: about.itriagehealth.com
1
6. Program To Print the
Numbers From 1 to 10
• The program prints the numbers from 1 to 10.
• The declaration names the control variable (counter),
declares it to be an integer, reserves space for it in memory
and sets it to an initial value of 1.
• Declarations that require initialization are executable statements.
• In C++, it’s more precise to call a declaration that also reserves memory a
definition.
• Variable counter also could have been declared and initialized.
• The next line increments the loop counter by 1 each time the loop’s body is
performed.
Image Credit: www.geticp.com
7. Program To Print the
Numbers From 1 to 10
• The loop-continuation condition in the while statement determines whether the
value of the control variable is less than or equal to 10 (the final value for which
the condition is true). The body of this while executes even when the control
variable is 10.
• The loop terminates when the control variable is greater than 10
(i.e., when counter is 11).
Image Credit: symsys.stanford.edu
8. Software Engineering Tips!
• Floating-point values are approximate, so controlling counting
loops with floating-point variables can result in imprecise
counter values and inaccurate tests for termination.
• Too many levels of nesting can make a program difficult to
understand. As a rule, try to void using more than three levels
of indentation.
• Control counting loops with integer values.
9. for Repetition Statement
• In addition to while, C++ provides the for repetition statement,
which specifies the counter-controlled repetition details in a single line of code.
• When the for statement begins executing, the control variable counter is declared
and initialized to 1. Then, the loop-continuation condition counter <= 10 is
checked. The initial value of counter is 1, so the condition is satisfied and the body
statement prints the value of counter, namely 1.
• Then, the expression ++counter increments control variable counter and the loop
begins again with the loop-continuation test. The control variable is now equal to
2, so the final value is not exceeded and the program performs the body statement
again.
• This process continues until the loop body has executed 10 times and the control
variable counter is incremented to 11—this causes the loop-continuation test to
fail and repetition to terminate.
• The program continues by performing the first statement after the for statement.
Image Credit: blog.hubspot.com2
10. for Statement Header Components
• Notice that the for statement header “does it all”—it specifies each of the items
needed for counter controlled repetition with a control variable.
• If there’s more than one statement in the body of the for, braces are required to
enclose the body of the loop.
11. Software Engineering Tips!
• Using an incorrect relational operator or using an incorrect
final value of a loop counter in the condition of a while or for
statement can cause off-by-one errors.
• Using the final value in the condition of a while or for
statement and using the <= relational operator will help avoid
off-by-one errors. For a loop used to print the values 1 to
10, for example, the loop-continuation condition should be
counter <= 10 rather than counter < 10 (which is an off-by-
one error) or counter < 11 (which is nevertheless correct).
Many programmers prefer so-called zero-based counting, in
which, to count 10 times through the loop, counter would be
initialized to zero and the loop-continuation test would be
counter < 10.
12. for Repetition Statement
• The general form of the for statement is
where the initialization expression initializes the loop’s control variable,
loopContinuationCondition determines whether the loop should continue
executing and increment increments the control variable.
• If the initialization expression declares the control variable (i.e., its type is specified
before its name), the control variable can be used only in the body of the for
statement— the control variable will be unknown outside the for statement. This
restricted use of the control variable name is known as the variable’s scope.
for ( initialization; loopContinuationCondition; increment )
statement
13. for Repetition Statement
• As we’ll see, the initialization and increment expressions can be comma-separated
lists of expressions.
• The commas, as used in these expressions, are comma operators, which
guarantee that lists of expressions evaluate from left to right.
• The comma operator has the lowest precedence of all C++ operators.
• The value and type of a comma-separated list of expressions is the value and type
of the rightmost expression.
• The comma operator is often used in for statements.
• Its primary application is to enable you to use multiple initialization expressions
and/or multiple increment expressions. For example, there may be several control
variables in a single for statement that must be initialized and incremented.
Image Credit: whatcommarketing.com
14. for Repetition Statement
• The three expressions in the for statement header are optional
(but the two semicolon separators are required).
• If the loopContinuationCondition is omitted, C++ assumes that the condition is
true, thus creating an infinite loop.
• One might omit the initialization expression if the control variable is initialized
earlier in the program.
• One might omit the increment expression if the increment is calculated by
statements in the body of the for or if no increment is needed.
Image Credit: recision.wordpress.com
15. Software Engineering Tips!
• Place only expressions involving the control variables in the
initialization and increment sections of a for statement.
• Placing a semicolon immediately to the right of the right
parenthesis of a for header makes the body of that for
statement an empty statement. This is usually a logic error.
16. for Repetition Statement
• The increment expression in the for statement acts as a stand-alone statement at
the end of the body of the for. Therefore, for integer counters, the expressions:
are all equivalent in the increment expression (when no other code appears there).
The integer variable being incremented here does not appear in a larger
expression, so both pre-incrementing and post-incrementing actually have the
same effect.
counter = counter + 1
counter += 1
++counter
counter++
Image Credit: balistrericonsulting.com
17. for Repetition Statement
• The initialization, loop-continuation condition and increment expressions of a for
statement can contain arithmetic expressions. For example, if x = 2 and y = 10, and
x and y are not modified in the loop body, the for header:
is equivalent to:
for ( int j = x; j <= 4 * x * y; j += y / x )
for ( int j = 2; j <= 80; j += 5 )
Image Credit: www.loopinsight.com
18. Software Engineering Tips!
• Although the value of the control variable can be changed in
the body of a for statement, avoid doing so, because this
practice can lead to subtle logic errors.
19. for Repetition Statement
• The “increment” of a for statement can be negative, in which case it’s really a
decrement and the loop actually counts downward.
• If the loop-continuation condition is initially false, the body of the for statement is
not performed. Instead, execution proceeds with the statement following the for.
• Frequently, the control variable is printed or used in calculations in the body of a
for statement, but this is not required. It’s common to use the control variable for
controlling repetition while never mentioning it in the body of the for statement.
Image Credit: blog.hsi.com
20. A Couple Of C++ Programing
Reminders
• To find the length of a string:
– string.length()
• To print out the character at the 5th location in
a string:
– cout << string[4] << endl;
• To get part of a string use:
– string.substr (3,5) where 3 is the starting location
and 5 is the number of characters to return.
Image Credit: yourfreewordpress.com
21. In-Class Programming Challenge
• Given the sentence:
“The quick brown fox jumps over the lazy dog”.
• Create a generic C++ program that will determine
which word has the most vowels in it and print that
word out.
23. for Statement
UML Activity Diagram
• The for repetition statement’s UML activity diagram is similar to that of the while
statement.
• Our diagram shows the activity diagram of the for statement.
• The diagram makes it clear that initialization occurs once before the loop-
continuation test is evaluated the first time, and that incrementing occurs each
time through the loop after the body statement executes.
• Note that (besides an initial state, transition arrows, a merge, a final state and
several notes) the diagram contains only action states and a decision.
Image Credit: content.prolifiq.com
24. Software Engineering Tips!
• Not using the proper relational operator in the loop-
continuation condition of a loop that counts downward (such
as incorrectly using i <= 1 instead of i >= 1 in a loop counting
down to 1) is a logic error that yields incorrect results when
the program runs.
• Although statements preceding a for and statements in the
body of a for often can be merged into the for header, doing
so can make the program more difficult to read, maintain,
modify and debug.
26. Application:
Compound Interest Calculations
• Consider the following problem statement:
A person invests $1000.00 in a savings account yielding 5 percent interest.
Assuming that all interest is left on deposit in the account, calculate and print the
amount of money in the account at the end of each year for 10 years. Use the
following formula for determining these amounts: a = p ( 1 + r )n
where
p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year.
Image Credit: tylertringas.com4
27. Application:
Compound Interest Calculations
• The for statement in our program performs the indicated calculation for each
of the 10 years the money remains on deposit, varying a control variable from 1 to
10 in increments of 1.
• C++ does not include an exponentiation operator, so we use the standard
library function pow . The function pow(x, y) calculates the value of x raised to
the yth power.
• In this example, the algebraic expression (1 + r)n is written as pow(1.0 +
rate, year), where variable rate represents r and variable year represents n.
Function pow takes two arguments of type double and returns a double value.
28. Application:
Compound Interest Calculations
• This program will not compile without including header <cmath> .
• Function pow requires two double arguments.
• Variable year is an integer.
• Header <cmath> includes information that tells the compiler to convert the value
of year to a temporary double representation before calling the function.
• This information is contained in pow’s function prototype.
Image Credit: smallbusiness.chron.com
29. Software Engineering Tips!
• Forgetting to include the appropriate header when using
standard library functions (e.g., <cmath> in a program that
uses math library functions) is a compilation error.
• Do not use variables of type float or double to perform
monetary calculations. The imprecision of floating-point
numbers can cause incorrect monetary values.
30. A Caution about Using Type float or
double for Monetary Amounts
• Here’s a simple explanation of what can go wrong when using float or double to
represent dollar amounts (assuming setprecision(2) is used to specify two digits of
precision when printing):
• Two dollar amounts stored in the machine could be 14.234 (which prints as 14.23)
and 18.673 (which prints as 18.67). When these amounts are added, they produce
the internal sum 32.907, which prints as 32.91. Thus your printout could appear
as:
• but a person adding the individual numbers as printed would expect the sum
32.90! You’ve been warned!
• [Note: Some third-party vendors sell C++ class libraries that perform precise
monetary calculations.]
31. Using Stream Manipulators to
Format Numeric Output
• The output statement in this program before the for loop and the output
statement in the for loop combine to print the values of the variables year and
amount with the formatting specified by the parameterized stream manipulators
setprecision and setw and the nonparameterized stream manipulator fixed.
• The stream manipulator setw(4) specifies that the next value output should
appear in a field width of 4—i.e., cout prints the value with at least 4 character
positions. If the value to be output is less than 4 character positions wide, the
value is right justified in the field by default. If the value to be output
is more than 4 character positions wide, the field width is extended to
accommodate the entire value.
• To indicate that values should be output left justified, simply output
nonparameterized stream manipulator left (found in header
<iostream>). Right justification can be restored by outputting
nonparameterized stream manipulator right.
Image Credit: www.turbosquid.com
32. Using Stream Manipulators to
Format Numeric Output
• The other formatting in the output statements indicates that variable
amount is printed as a fixed-point value with a decimal point (specified
with the stream manipulator fixed) right justified in a field of 21 character
positions (specified with setw(21)) and two digits of precision to the right of the
decimal point (specified with manipulator setprecision(2)).
• We applied the stream manipulators fixed and setprecision to the output stream
(i.e., cout) before the for loop because these format settings remain in effect until
they’re changed—such settings are called sticky settings and they do not need to
be applied during each iteration of the loop.
• However, the field width specified with setw applies only to the next value output.
• The calculation 1.0 + rate, which appears as an argument to the pow function, is
contained in the body of the for statement. In fact, this calculation produces the
same result during each iteration of the loop, so repeating it is wasteful—it should
be performed once before the loop.
Image Credit: www.cheec.net
33. do…while Repetition Statement
• The do…while repetition statement is similar to the while statement.
• In the while statement, the loop-continuation condition test occurs at the
beginning of the loop before the body of the loop executes. The do…while
statement tests the loop-continuation condition after the loop body executes;
therefore, the loop body always executes at least once.
• When a do…while terminates, execution continues with the statement after the
while clause.
• It’s not necessary to use braces in the do…while statement if there’s only one
statement in the body; however, most programmers include the braces to avoid
confusion between the while and do…while statements.
Image Credit: www.iconshock.com
34. Program: uses a do…while statement
to print the numbers 1–10
35. do…while Statement UML Activity
Diagram
This diagram makes
it clear that the loop-
continuation
condition is not
evaluated until after
the loop performs its
body at least once.
36. Software Engineering Tips!
• Avoid placing expressions whose values do not change inside
loops—but, even if you do, many of today’s sophisticated
optimizing compilers will automatically place such
expressions outside the loops in the generated machine-
language code.
• Many compilers contain optimization features that improve the
performance of the code you write, but it’s still better to write
good code from the start.
37. What We Covered Today
1. We then discussed the while repetition
statement, where a set of statements are
executed repeatedly as long as a condition is
true.
2. We used control-statement stacking to total
and compute the average of a set of student
grades with counter- and sentinel-controlled
repetition, and we used control statement
nesting to analyze and make decisions based
on a set of exam results.
3. We introduced assignment operators, which
can be used for abbreviating statements. We
presented the increment and decrement
operators, which can be used to add or
subtract the value 1 from a variable. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
38. What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For do…While
39. What We’ll Be Covering Next Time
1. How to define a class
and use it to create an
object.
2. How to implement a
class’s behaviors as
member functions.
3. How to implement a
class’s attributes as
data members.Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
40. An Introduction To Software
Development Using C++
Class #3:
Variables, Math
41. Today’s In-Class C++
Programming Assignment
• Write a program that reads in the size of the side of a square and then
prints a hollow square of that size out of asterisks and blanks.
• Your program should work for squares of all side sizes between 1 and 20.
For example, if your program reads a size of 5, it should print:
Image Credit:: study.com
42. Answer To Today’s Challenge
// In-Class Exercise #7 - Squares
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int side, rowPosition, size;
cout << "Enter the square side: ";
cin >> side;
size = side;
while ( side > 0 ) {
rowPosition = size;
while ( rowPosition > 0 ) {
if ( size == side || side == 1 || rowPosition == 1 ||
rowPosition == size )
cout << '*';
else
cout << ' ';
--rowPosition;
}
cout << 'n';
--side;
}
cout << endl;
return 0;
}
Image Credit: getentrepreneurial.com
43. What We Covered Today
1. Got graphical!
2. Created a program to
print out a square of
whatever size we choose!
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
44. What We’ll Be Covering Next Time
1. Binary conversions
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
Notas do Editor
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.