SlideShare a Scribd company logo
An Introduction To Software
Development Using C++
Class #11:
Converting between
types, formatting
floating point,
increment / decrement
operators
Implementing Sentinel-Controlled
Repetition in Class GradeBook
• In this version of the program we show class GradeBook containing
member function determineClassAverage that implements the
pseudocode algorithm
• Although each grade entered is an integer, the averaging calculation
is likely to produce a number with a decimal point—in other words,
a real number or floating-point number (e.g., 7.33, 0.0975 or 1000.12345).
• The type int cannot represent such a number, so this class must use another type
to do so.
• C++ provides several data types for storing floating-point numbers in memory,
including float and double. The primary difference between these types is that,
compared to float variables, double variables can typically store numbers with
larger magnitude and finer detail (i.e., more digits to the right of the decimal
point—also known as the number’s precision).
• This program introduces a special operator called a cast operator to force the
averaging calculation to produce a floating-point numeric result.
1
Class average problem using
sentinel-controlled repetition
Software Engineering Tips!
• Omitting the braces that delimit a block can lead to logic
errors, such as infinite loops. To prevent this problem, some
programmers enclose the body of every control statement in
braces, even if the body contains only a single statement.
• Using floating-point numbers in a manner that assumes
they’re represented exactly (e.g., using them in comparisons
for equality) can lead to incorrect results. Floating-point
numbers are represented only approximately.
Floating-Point Number Precision and
Memory Requirements
• Variables of type float represent single-precision floating-point
numbers and have approximately seven significant digits on most
32-bit systems.
• Variables of type double represent double-precision floating-point numbers. These
require twice as much memory as float variables and provide approximately 15
significant digits on most 32-bit systems—approximately double the precision of
float variables.
• Most programmers represent floating-point numbers with type double. In fact,
C++ treats all floating-point numbers you type in a program’s source code (such as
7.33 and 0.0975) as double values by default. Such values in the source code are
known as floating-point constants.
• In conventional arithmetic, floating-point numbers often arise as a result of
division—10 divided by 3, the result is 3.3333333…. The computer allocates only a
fixed amount of space to hold such a value, so clearly the stored floating-point
value can be only an approximation. Image Credit: raymondclarkeimages
Floating-Point Number Precision and
Memory Requirements
• Although floating-point numbers are not always 100 percent precise, they have
numerous applications.
• For example, when we speak of a “normal” body temperature of 98.6, we do not
need to be precise to a large number of digits. When we read the temperature on
a thermometer as 98.6, it may actually be 98.5999473210643.
• Calling this number simply 98.6 is fine for most applications involving body
temperatures.
• Due to the imprecise nature of floating-point numbers, type double is preferred
over type float, because double variables can represent floating-point numbers
more accurately. For this reason, we will type double throughout our code
examples.
Image Creditwww.marketing-schools.org
Converting Between Fundamental
Types Explicitly and Implicitly
• In our code, the variable average is declared to be of type double to capture the
fractional result of our calculation.
• However, total and gradeCounter are both integer variables.
• Recall that dividing two integers results in integer division, in which any fractional
part of the calculation is lost truncated).
• In the following statement:
• the division occurs first—the result’s fractional part is lost before it’s assigned to
average.
average = total / gradeCounter;
Image Credit: www.fastbooking.com
Converting Between Fundamental
Types Explicitly and Implicitly
• To perform a floating-point calculation with integers, we must create temporary
floatingpoint values.
• C++ provides the unary cast operator to accomplish this task.
• We use the cast operator static_cast<double>(total) to create a temporary
floating-point copy of its operand in parentheses—total.
• Using a cast operator in this manner is called explicit conversion. The value stored
in total is still an integer.
• The calculation now consists of a floating-point value (the temporary double
version of total) divided by the integer gradeCounter.
Image Credit: www.mag-corp.com
Converting Between Fundamental
Types Explicitly and Implicitly
• The compiler knows how to evaluate only expressions in which the operand types
are identical. To ensure that the operands are of the same type, the compiler
performs an operation called promotion (also called implicit conversion) on
selected operands.
• For example, in an expression containing values of data types int and double, C++
promotes int operands to double values.
• In our example, we are treating total as a double (by using the unary cast
operator), so the compiler promotes gradeCounter to double, allowing the
calculation to be performed—the result of the floating-point division is assigned to
average.
Image Credit: www.thinkwithgoogle.com
Converting Between Fundamental
Types Explicitly and Implicitly
• Cast operators are available for use with every data type and with class types as
well.
• The static_cast operator is formed by following keyword static_cast with angle
brackets (< and >) around a data-type name. The cast operator is a unary
operator—an operator that takes only one operand.
• Cast operators have higher precedence than other unary operators, such as unary
+ and unary -. This precedence is higher than that of the multiplicative operators *,
/ and %, and lower than that of parentheses.
Image Credit: www.volacci.com
Formatting for
Floating-Point Numbers
• The call to setprecision in our program (with an argument of 2) indicates that
double variable average should be printed with two digits of precision to the right
of the decimal point (e.g., 92.37).
• This call is referred to as a parameterized stream manipulator
(because of the 2 in parentheses).
• Programs that use these calls must contain the preprocessor directive:
• The manipulator endl is a nonparameterized stream manipulator (because it isn’t
followed by a value or expression in parentheses) and does not require the
<iomanip> header.
• If the precision is not specified, floating-point values are normally output with six
digits of precision (i.e., the default precision on most 32-bit systems today).
#include <iomanip>
Image Credit: www.ebay.com
Formatting for
Floating-Point Numbers
• The stream manipulator fixed indicates that floating-point values should be
output in so-called fixed-point format, as opposed to scientific notation.
• Scientific notation is a way of displaying a number as a floating-point number
between the values of 1.0 and 10.0, multiplied by a power of 10.
• For instance, the value 3,100.0 would be displayed in scientific notation as
3.1 × 103. Scientific notation is useful when displaying values that are very large or
very small.
• Fixed-point formatting, on the other hand, is used to force a floating-point
number to display a specific number of digits. Specifying fixed-point formatting
also forces the decimal point and trailing zeros to print, even if the value is a whole
number amount, such as 88.00.
• Without the fixed-point formatting option, such a value prints in C++ as 88 without
the trailing zeros and without the decimal point.
Image Credit: www.vectorstock.com
Formatting for
Floating-Point Numbers
• When the stream manipulators fixed and setprecision are used in a program, the
printed value is rounded to the number of decimal positions indicated by the value
passed to setprecision (e.g., the value 2 in our program), although the value in
memory remains unaltered. |
• For example, the values 87.946 and 67.543 are output as 87.95 and 67.54,
respectively.
• It’s also possible to force a decimal point to appear by using stream manipulator
showpoint. If showpoint is specified without fixed, then trailing zeros will not
print. Like endl, stream manipulators fixed and showpoint do not use parameters,
nor do they require the <iomanip> header.
• Both can be found in header <iostream>.
Image Credit: www.directindustry.com
Formatting for
Floating-Point Numbers
• The program outputs the class average rounded to the nearest hundredth and
with exactly two digits to the right of the decimal point.
• The parameterized stream manipulator indicates that variable average’s value
should be displayed with two digits of precision to the right of the decimal point—
indicated by setprecision( 2 ).
• The three grades entered during the sample execution of the program
in total 257, which yields the average 85.666666….
Image Credit: www.dreamstime.com
Formulating Algorithms:
Nested Control Statements
• For the next example, we once again formulate an algorithm by using pseudocode
and topdown, stepwise refinement, and write a corresponding C++ program.
• We’ve seen that control statements can be stacked on top of one another (in
sequence). Here, we examine the only other structured way control statements
can be connected, namely, by nesting one control statement within another.
Image Credit: www.thetelecomblog.com
Formulating Algorithms:
Nested Control Statements
• Consider the following problem statement:
A college offers a course that prepares students for the state licensing exam for real
estate brokers. Last year, ten of the students who completed this course took the exam.
The college wants to know how well its students did on the exam. You’ve been asked to
write a program to summarize the results. You’ve been given a list of these 10
students. Next to each name is written a 1 if the student passed the exam or a 2 if the
student failed.
• Your program should analyze the results of the exam as follows:
1. Input each test result (i.e., a 1 or a 2). Display the prompting message
“Enter result” each time the program requests another test result.
2. Count the number of test results of each type.
3. Display a summary of the test results indicating the number of
students who passed and the number who failed.
4. If more than eight students passed the exam, print the message
“Bonus to instructor!” Image Credit: german.yale.edu
Formulating Algorithms:
Nested Control Statements
After reading the problem statement carefully, we make the following observations:
1. The program must process test results for 10 students. A counter-controlled loop
can be used because the number of test results is known in advance.
2. Each test result is a number—either a 1 or a 2. Each time the program reads a test
result, the program must determine whether the number is a 1 or a 2. We test for
a 1 in our algorithm. If the number is not a 1, we assume that it’s a 2.
3. Two counters are used to keep track of the exam results—one to count the number
of students who passed the exam and one to count the number of students
who failed the exam.
4. After the program has processed all the results, it must decide whether more than
eight students passed the exam.
Image Credit: www.lightingschool.eu
Formulating Algorithms:
Nested Control Statements
• Let’s proceed with top-down, stepwise refinement. We begin with a pseudocode
representation of the top:
• Once again, it’s important to emphasize that the top is a complete representation
of the program, but several refinements are likely to be needed before the
pseudocode evolves naturally into a C++ program.
• Our first refinement is:
Analyze exam results and decide whether a bonus should be paid
Initialize variables
Input the 10 exam results, and count passes and failures
Display a summary of the exam results and decide whether a bonus should be paid
Image Credit: fullcircleinsights.com
Formulating Algorithms:
Nested Control Statements
• Even though we have a complete representation of the entire program, further
refinement is necessary.
• We now commit to specific variables. Counters are needed to record the passes
and failures, a counter will be used to control the looping process and a variable is
needed to store the user input.
• The last variable is not initialized, because its value is read from the user during
each iteration of the loop.
• The pseudocode statement
• can be refined as follows:
Initialize variables
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
Image Credit: caladay.wordpress.com
Formulating Algorithms:
Nested Control Statements
• Notice that only the counters are initialized at the start of the algorithm.
• The pseudocode statement:
• requires a loop that successively inputs the result of each exam. Here it’s known in
advance that there are precisely 10 exam results, so counter-controlled looping is
appropriate.
• Inside the loop (i.e., nested within the loop), an if…else statement will determine
whether each exam result is a pass or a failure and will increment the appropriate
counter. The refinement of the preceding pseudocode statement is then:
Input the 10 exam results, and count passes and failures
While student counter is less than or equal to 10
Prompt the user to enter the next exam result
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
Image Credit: www.convertwithcontent.com
Formulating Algorithms:
Nested Control Statements
• The pseudocode statement:
• can be refined as follows:
Display a summary of the exam results and decide whether a bonus should be paid
Display the number of passes
Display the number of failures
If more than eight students passed
Display “Bonus to instructor!”
Image Credit: www.realsuccess.net
Pseudocode for
examination-results problem.
1 Initialize passes to zero
2 Initialize failures to zero
3 Initialize student counter to one
4
5 While student counter is less than or equal to 10
6 Prompt the user to enter the next exam result
7 Input the next exam result
8
9 If the student passed
10 Add one to passes
11 Else
12 Add one to failures
13
14 Add one to student counter
15
16 Display the number of passes
17 Display the number of failures
18
19 If more than eight students passed
20 Display “Bonus to instructor!”
Image Credit: www.bfoit.org
Conversion to Class Analysis
• Our next program implements the pseudocode.
• This example does not contain a class—it contains just
a source code file with function main performing all the
application’s work.
• This source code file contained function main, which created an object of the class
and called its member functions. Occasionally, when it does not make sense to try
to create a reusable class to demonstrate a concept, we’ll use an example
contained entirely within the main function of a single source code file.
• The program declares the variables used to process the examination results. We’ve
taken advantage of a feature of C++ that allows variable initialization to be
incorporated into declarations (passes is initialized to 0, failures is initialized to 0
and studentCounter is initialized to 1).
Image Credit: www.freshideawebsites.com2
Conversion to Class Analysis
• The while statement in the program loops 10 times. Each iteration inputs and
processes one exam result.
• The if…else statement for processing each result is nested in the while statement.
If the result is 1, the if…else statement increments passes; otherwise, it assumes
the result is 2 and increments failures.
• The program increments studentCounter before the loop condition is tested again.
After 10 values have been input, the loop terminates and the program displays the
number of passes and the number of failures.
• The if statement in determines whether more than eight students passed the
exam and, if so, outputs the message "Bonus to instructor!".
Image Credit: www.youronlinesuccess.com.au
Program Output
Assignment Operators
• C++ provides several assignment operators for
abbreviating assignment expressions.
• For example, the statement:
can be abbreviated with the addition assignment operator += as:
which adds the value of the expression on the operator’s right to the value of the
variable on the operator’s left and stores the result in the left-side variable.
c = c + 3;
c += 3;
Image Credit: www.wpclipart.com
Assignment Operators
• Any statement of the form:
in which the same variable appears on both sides of the assignment operator and
operator is one of the binary operators +, -, *, /, or %, can be written in the form:
variable = variable operator expression;
variable operator= expression;
Increment and Decrement
Operators
• In addition to the arithmetic assignment operators,
C++ also provides two unary operators for adding 1 to
or subtracting 1 from the value of a numeric variable.
• These are the unary increment operator, ++, and the unary decrement operator, --.
• A program can increment by 1 the value of a variable called c using the increment
operator, ++, rather than the expression c = c + 1 or c += 1.
• An increment or decrement operator that’s prefixed to (placed before) a variable is
referred to as the prefix increment or prefix decrement operator, respectively.
• An increment or decrement operator that’s postfixed to (placed after) a variable is
referred to as the postfix increment or postfix decrement operator, respectively.
Image Credit: www.property118.com
Software Engineering Tips!
• Unlike binary operators, the unary increment and decrement
operators should be placed next to their operands, with no
intervening spaces.
• Attempting to use the increment or decrement operator on an
expression other than a modifiable variable name or
reference, e.g., writing ++(x + 1), is a syntax error.
Increment and Decrement
Operators
Preincrementing and
postincrementing.
3
What We Covered Today
1. 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.
2. 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/
What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
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/
An Introduction To Software
Development Using C++
Class #3:
Variables, Math
Homework #2:
A Smarter Stoplight Problem
• Smallville is basically happy with the 4-way signal control system that you
designed for them. However, now they want to make some changes:
– The lights in your system need to change color based primarily on the passage of time.
– Change your program so that green lights last for 12 seconds, yellow lights last for 3
seconds and red lights last until the light turns green again.
– Priority support for Smallville emergency vehicles needs to be added.
– Run the program for 60 seconds.
– At 35 seconds into the simulation, simulate an emergency vehicle approaching the East
traffic light.
– At 45 seconds simulate the emergency vehicle moving on and the system returning to
normal.
• Rules
– You must modify Dr. Anderson's solution to HW #1 to create your solution to this
homework.
– You must use a class in your solution.
– You must declare at least 4 objects in your solution.
How To Make Really, Really Long
IF Statements: Logical Operators
• The operator ! is the C++ operator for the Boolean operation NOT. It has only one
operand, to its right, and inverts it, producing false if its operand is true, and true if
its operand is false. Basically, it returns the opposite Boolean value of evaluating its
operand.
• The logical operators && and || are used when evaluating
two expressions to obtain a single relational result.
• The operator && corresponds to the Boolean logical operation AND, which yields
true if both its operands are true, and false otherwise.
• The operator || corresponds to the Boolean logical operation OR, which yields
true if either of its operands is true, thus being false only when both operands are
false.
• When using the logical operators, C++ only evaluates what is necessary from left to
right to come up with the combined relational result, ignoring the rest. This is
known as short-circuit evaluation Image Credit: www.linkedin.com
Logical Operators: Examples!
Today’s In-Class C++
Programming Assignment
• Develop a C++ program that will
determine if a department store
customer has exceeded the credit
limit on a charge account. For
each customer, the following
facts are available:
a) Account number (an integer)
b) Balance at the beginning of the month
c) Total of all items charged by this
customer this month
d) Total of all credits applied to this
customer's account this month
e) Allowed credit limit
• The program should input each of
these facts, calculate the new
balance (= beginning balance +
charges – credits) and determine
if the new balance exceeds the
customer's credit limit. For those
customers whose credit limit is
exceeded, the program should
display the customer's account
number, credit limit, new balance
and the message “Credit limit
exceeded”.
Image Credit:: www.accpc.com
What Should This Program
Look Like?
Answer To Today’s Challenge
// In-Class Exercise #6 - Credit Card
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <iomanip>
int main()
{
int accountNumber;
double balance, charges, credits, limit;
cout << "Enter account number (-1 to end): ";
cin >> accountNumber;
while ( accountNumber != -1 ) {
cout << "Enter beginning balance: ";
cin >> balance;
cout << "Enter total charges: ";
cin >> charges;
cout << "Enter total credits: ";
cin >> credits;
cout << "Enter credit limit: ";
cin >> limit;
balance += charges - credits;
if ( balance > limit )
cout << "Account: " << accountNumber
<< "nCredit limit: " << limit
<< "nBalance: " << balance
<< "nCredit Limit Exceeded.n";
cout << "nEnter account number (-1 to end): ";
cin >> accountNumber;
}
cout << endl; // ensure all output is displayed
return 0;
}
Image Creditigoglobal.org
What We Covered Today
1. An introduction to
keeping track of credit
card payments.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. Palindromes
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

More Related Content

What's hot

As Level Computer Science Book -2
As Level Computer Science  Book -2As Level Computer Science  Book -2
As Level Computer Science Book -2
DIGDARSHAN KUNWAR
 
Flowcharts
FlowchartsFlowcharts
Flowcharts
solielmutya
 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
SzeChingChen
 
Sequence diagrams
Sequence diagramsSequence diagrams
Sequence diagrams
Preeti Mishra
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programming
Dhrumil Panchal
 
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision tableProgramming aids- Algorithm, Flowchart, Pseudocodes and Decision table
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
Anjali Technosoft
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Anshumali Singh
 
Unit 1-problem solving with algorithm
Unit 1-problem solving with algorithmUnit 1-problem solving with algorithm
Unit 1-problem solving with algorithm
rajkumar1631010038
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowchart
hermiraguilar
 
Visual Logic Project - 1
Visual Logic Project - 1Visual Logic Project - 1
Visual Logic Project - 1
Programming Techniques and Algorithms
 
Ch10 Program Organization
Ch10 Program OrganizationCh10 Program Organization
Ch10 Program Organization
SzeChingChen
 
The Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialThe Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram Tutorial
Creately
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
Rasan Samarasinghe
 
Flow charts
Flow chartsFlow charts
Flow charts
Aditya Sharat
 
Slide 4 Interaction Diagram
Slide 4 Interaction DiagramSlide 4 Interaction Diagram
Slide 4 Interaction Diagram
Niloy Rocker
 
Unit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingUnit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programming
Abha Damani
 
Online Advance Excel & VBA Training in India
 Online Advance Excel & VBA Training in India Online Advance Excel & VBA Training in India
Online Advance Excel & VBA Training in India
ibinstitute0
 
Prg 211 prg211
Prg 211 prg211Prg 211 prg211
Prg 211 prg211
GOODCourseHelp
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnity
mazenet
 
Sequence diagrame
Sequence diagrameSequence diagrame
Sequence diagrame
City University
 

What's hot (20)

As Level Computer Science Book -2
As Level Computer Science  Book -2As Level Computer Science  Book -2
As Level Computer Science Book -2
 
Flowcharts
FlowchartsFlowcharts
Flowcharts
 
Ch9 Functions
Ch9 FunctionsCh9 Functions
Ch9 Functions
 
Sequence diagrams
Sequence diagramsSequence diagrams
Sequence diagrams
 
Type conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programmingType conversion, precedence, associativity in c programming
Type conversion, precedence, associativity in c programming
 
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision tableProgramming aids- Algorithm, Flowchart, Pseudocodes and Decision table
Programming aids- Algorithm, Flowchart, Pseudocodes and Decision table
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Unit 1-problem solving with algorithm
Unit 1-problem solving with algorithmUnit 1-problem solving with algorithm
Unit 1-problem solving with algorithm
 
Programming process and flowchart
Programming process and flowchartProgramming process and flowchart
Programming process and flowchart
 
Visual Logic Project - 1
Visual Logic Project - 1Visual Logic Project - 1
Visual Logic Project - 1
 
Ch10 Program Organization
Ch10 Program OrganizationCh10 Program Organization
Ch10 Program Organization
 
The Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialThe Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram Tutorial
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
Flow charts
Flow chartsFlow charts
Flow charts
 
Slide 4 Interaction Diagram
Slide 4 Interaction DiagramSlide 4 Interaction Diagram
Slide 4 Interaction Diagram
 
Unit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingUnit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programming
 
Online Advance Excel & VBA Training in India
 Online Advance Excel & VBA Training in India Online Advance Excel & VBA Training in India
Online Advance Excel & VBA Training in India
 
Prg 211 prg211
Prg 211 prg211Prg 211 prg211
Prg 211 prg211
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnity
 
Sequence diagrame
Sequence diagrameSequence diagrame
Sequence diagrame
 

Similar to Intro To C++ - Class 11 - Converting between types, formatting floating point, increment / decrement operators

C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
Thapar Institute
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
C programming language
C programming languageC programming language
C programming language
Abin Rimal
 
Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
MLG College of Learning, Inc
 
Aspdot
AspdotAspdot
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
marvellous2
 
Lamborghini Veneno Allegheri #2004@f**ck
Lamborghini Veneno Allegheri #2004@f**ckLamborghini Veneno Allegheri #2004@f**ck
Lamborghini Veneno Allegheri #2004@f**ck
seidounsemel
 
C++
C++C++
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
chaithracs3
 
lec 2.pptx
lec 2.pptxlec 2.pptx
lec 2.pptx
AhsanAli64749
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++
Aahwini Esware gowda
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
Dr.Florence Dayana
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
Tekendra Nath Yogi
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
Ralph Weber
 
C program
C programC program
C program
AJAL A J
 

Similar to Intro To C++ - Class 11 - Converting between types, formatting floating point, increment / decrement operators (20)

C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
C programming language
C programming languageC programming language
C programming language
 
Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
Aspdot
AspdotAspdot
Aspdot
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lamborghini Veneno Allegheri #2004@f**ck
Lamborghini Veneno Allegheri #2004@f**ckLamborghini Veneno Allegheri #2004@f**ck
Lamborghini Veneno Allegheri #2004@f**ck
 
C++
C++C++
C++
 
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
 
lec 2.pptx
lec 2.pptxlec 2.pptx
lec 2.pptx
 
c-programming
c-programmingc-programming
c-programming
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
C program
C programC program
C program
 

Recently uploaded

BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
Mohammad Al-Dhahabi
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Juneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School DistrictJuneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School District
David Douglas School District
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
سمير بسيوني
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 

Recently uploaded (20)

BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Juneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School DistrictJuneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School District
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdfمصحف القراءات العشر   أعد أحرف الخلاف سمير بسيوني.pdf
مصحف القراءات العشر أعد أحرف الخلاف سمير بسيوني.pdf
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 

Intro To C++ - Class 11 - Converting between types, formatting floating point, increment / decrement operators

  • 1. An Introduction To Software Development Using C++ Class #11: Converting between types, formatting floating point, increment / decrement operators
  • 2. Implementing Sentinel-Controlled Repetition in Class GradeBook • In this version of the program we show class GradeBook containing member function determineClassAverage that implements the pseudocode algorithm • Although each grade entered is an integer, the averaging calculation is likely to produce a number with a decimal point—in other words, a real number or floating-point number (e.g., 7.33, 0.0975 or 1000.12345). • The type int cannot represent such a number, so this class must use another type to do so. • C++ provides several data types for storing floating-point numbers in memory, including float and double. The primary difference between these types is that, compared to float variables, double variables can typically store numbers with larger magnitude and finer detail (i.e., more digits to the right of the decimal point—also known as the number’s precision). • This program introduces a special operator called a cast operator to force the averaging calculation to produce a floating-point numeric result. 1
  • 3. Class average problem using sentinel-controlled repetition
  • 4. Software Engineering Tips! • Omitting the braces that delimit a block can lead to logic errors, such as infinite loops. To prevent this problem, some programmers enclose the body of every control statement in braces, even if the body contains only a single statement. • Using floating-point numbers in a manner that assumes they’re represented exactly (e.g., using them in comparisons for equality) can lead to incorrect results. Floating-point numbers are represented only approximately.
  • 5. Floating-Point Number Precision and Memory Requirements • Variables of type float represent single-precision floating-point numbers and have approximately seven significant digits on most 32-bit systems. • Variables of type double represent double-precision floating-point numbers. These require twice as much memory as float variables and provide approximately 15 significant digits on most 32-bit systems—approximately double the precision of float variables. • Most programmers represent floating-point numbers with type double. In fact, C++ treats all floating-point numbers you type in a program’s source code (such as 7.33 and 0.0975) as double values by default. Such values in the source code are known as floating-point constants. • In conventional arithmetic, floating-point numbers often arise as a result of division—10 divided by 3, the result is 3.3333333…. The computer allocates only a fixed amount of space to hold such a value, so clearly the stored floating-point value can be only an approximation. Image Credit: raymondclarkeimages
  • 6. Floating-Point Number Precision and Memory Requirements • Although floating-point numbers are not always 100 percent precise, they have numerous applications. • For example, when we speak of a “normal” body temperature of 98.6, we do not need to be precise to a large number of digits. When we read the temperature on a thermometer as 98.6, it may actually be 98.5999473210643. • Calling this number simply 98.6 is fine for most applications involving body temperatures. • Due to the imprecise nature of floating-point numbers, type double is preferred over type float, because double variables can represent floating-point numbers more accurately. For this reason, we will type double throughout our code examples. Image Creditwww.marketing-schools.org
  • 7. Converting Between Fundamental Types Explicitly and Implicitly • In our code, the variable average is declared to be of type double to capture the fractional result of our calculation. • However, total and gradeCounter are both integer variables. • Recall that dividing two integers results in integer division, in which any fractional part of the calculation is lost truncated). • In the following statement: • the division occurs first—the result’s fractional part is lost before it’s assigned to average. average = total / gradeCounter; Image Credit: www.fastbooking.com
  • 8. Converting Between Fundamental Types Explicitly and Implicitly • To perform a floating-point calculation with integers, we must create temporary floatingpoint values. • C++ provides the unary cast operator to accomplish this task. • We use the cast operator static_cast<double>(total) to create a temporary floating-point copy of its operand in parentheses—total. • Using a cast operator in this manner is called explicit conversion. The value stored in total is still an integer. • The calculation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. Image Credit: www.mag-corp.com
  • 9. Converting Between Fundamental Types Explicitly and Implicitly • The compiler knows how to evaluate only expressions in which the operand types are identical. To ensure that the operands are of the same type, the compiler performs an operation called promotion (also called implicit conversion) on selected operands. • For example, in an expression containing values of data types int and double, C++ promotes int operands to double values. • In our example, we are treating total as a double (by using the unary cast operator), so the compiler promotes gradeCounter to double, allowing the calculation to be performed—the result of the floating-point division is assigned to average. Image Credit: www.thinkwithgoogle.com
  • 10. Converting Between Fundamental Types Explicitly and Implicitly • Cast operators are available for use with every data type and with class types as well. • The static_cast operator is formed by following keyword static_cast with angle brackets (< and >) around a data-type name. The cast operator is a unary operator—an operator that takes only one operand. • Cast operators have higher precedence than other unary operators, such as unary + and unary -. This precedence is higher than that of the multiplicative operators *, / and %, and lower than that of parentheses. Image Credit: www.volacci.com
  • 11. Formatting for Floating-Point Numbers • The call to setprecision in our program (with an argument of 2) indicates that double variable average should be printed with two digits of precision to the right of the decimal point (e.g., 92.37). • This call is referred to as a parameterized stream manipulator (because of the 2 in parentheses). • Programs that use these calls must contain the preprocessor directive: • The manipulator endl is a nonparameterized stream manipulator (because it isn’t followed by a value or expression in parentheses) and does not require the <iomanip> header. • If the precision is not specified, floating-point values are normally output with six digits of precision (i.e., the default precision on most 32-bit systems today). #include <iomanip> Image Credit: www.ebay.com
  • 12. Formatting for Floating-Point Numbers • The stream manipulator fixed indicates that floating-point values should be output in so-called fixed-point format, as opposed to scientific notation. • Scientific notation is a way of displaying a number as a floating-point number between the values of 1.0 and 10.0, multiplied by a power of 10. • For instance, the value 3,100.0 would be displayed in scientific notation as 3.1 × 103. Scientific notation is useful when displaying values that are very large or very small. • Fixed-point formatting, on the other hand, is used to force a floating-point number to display a specific number of digits. Specifying fixed-point formatting also forces the decimal point and trailing zeros to print, even if the value is a whole number amount, such as 88.00. • Without the fixed-point formatting option, such a value prints in C++ as 88 without the trailing zeros and without the decimal point. Image Credit: www.vectorstock.com
  • 13. Formatting for Floating-Point Numbers • When the stream manipulators fixed and setprecision are used in a program, the printed value is rounded to the number of decimal positions indicated by the value passed to setprecision (e.g., the value 2 in our program), although the value in memory remains unaltered. | • For example, the values 87.946 and 67.543 are output as 87.95 and 67.54, respectively. • It’s also possible to force a decimal point to appear by using stream manipulator showpoint. If showpoint is specified without fixed, then trailing zeros will not print. Like endl, stream manipulators fixed and showpoint do not use parameters, nor do they require the <iomanip> header. • Both can be found in header <iostream>. Image Credit: www.directindustry.com
  • 14. Formatting for Floating-Point Numbers • The program outputs the class average rounded to the nearest hundredth and with exactly two digits to the right of the decimal point. • The parameterized stream manipulator indicates that variable average’s value should be displayed with two digits of precision to the right of the decimal point— indicated by setprecision( 2 ). • The three grades entered during the sample execution of the program in total 257, which yields the average 85.666666…. Image Credit: www.dreamstime.com
  • 15. Formulating Algorithms: Nested Control Statements • For the next example, we once again formulate an algorithm by using pseudocode and topdown, stepwise refinement, and write a corresponding C++ program. • We’ve seen that control statements can be stacked on top of one another (in sequence). Here, we examine the only other structured way control statements can be connected, namely, by nesting one control statement within another. Image Credit: www.thetelecomblog.com
  • 16. Formulating Algorithms: Nested Control Statements • Consider the following problem statement: A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, ten of the students who completed this course took the exam. The college wants to know how well its students did on the exam. You’ve been asked to write a program to summarize the results. You’ve been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed. • Your program should analyze the results of the exam as follows: 1. Input each test result (i.e., a 1 or a 2). Display the prompting message “Enter result” each time the program requests another test result. 2. Count the number of test results of each type. 3. Display a summary of the test results indicating the number of students who passed and the number who failed. 4. If more than eight students passed the exam, print the message “Bonus to instructor!” Image Credit: german.yale.edu
  • 17. Formulating Algorithms: Nested Control Statements After reading the problem statement carefully, we make the following observations: 1. The program must process test results for 10 students. A counter-controlled loop can be used because the number of test results is known in advance. 2. Each test result is a number—either a 1 or a 2. Each time the program reads a test result, the program must determine whether the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it’s a 2. 3. Two counters are used to keep track of the exam results—one to count the number of students who passed the exam and one to count the number of students who failed the exam. 4. After the program has processed all the results, it must decide whether more than eight students passed the exam. Image Credit: www.lightingschool.eu
  • 18. Formulating Algorithms: Nested Control Statements • Let’s proceed with top-down, stepwise refinement. We begin with a pseudocode representation of the top: • Once again, it’s important to emphasize that the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode evolves naturally into a C++ program. • Our first refinement is: Analyze exam results and decide whether a bonus should be paid Initialize variables Input the 10 exam results, and count passes and failures Display a summary of the exam results and decide whether a bonus should be paid Image Credit: fullcircleinsights.com
  • 19. Formulating Algorithms: Nested Control Statements • Even though we have a complete representation of the entire program, further refinement is necessary. • We now commit to specific variables. Counters are needed to record the passes and failures, a counter will be used to control the looping process and a variable is needed to store the user input. • The last variable is not initialized, because its value is read from the user during each iteration of the loop. • The pseudocode statement • can be refined as follows: Initialize variables Initialize passes to zero Initialize failures to zero Initialize student counter to one Image Credit: caladay.wordpress.com
  • 20. Formulating Algorithms: Nested Control Statements • Notice that only the counters are initialized at the start of the algorithm. • The pseudocode statement: • requires a loop that successively inputs the result of each exam. Here it’s known in advance that there are precisely 10 exam results, so counter-controlled looping is appropriate. • Inside the loop (i.e., nested within the loop), an if…else statement will determine whether each exam result is a pass or a failure and will increment the appropriate counter. The refinement of the preceding pseudocode statement is then: Input the 10 exam results, and count passes and failures While student counter is less than or equal to 10 Prompt the user to enter the next exam result Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Image Credit: www.convertwithcontent.com
  • 21. Formulating Algorithms: Nested Control Statements • The pseudocode statement: • can be refined as follows: Display a summary of the exam results and decide whether a bonus should be paid Display the number of passes Display the number of failures If more than eight students passed Display “Bonus to instructor!” Image Credit: www.realsuccess.net
  • 22. Pseudocode for examination-results problem. 1 Initialize passes to zero 2 Initialize failures to zero 3 Initialize student counter to one 4 5 While student counter is less than or equal to 10 6 Prompt the user to enter the next exam result 7 Input the next exam result 8 9 If the student passed 10 Add one to passes 11 Else 12 Add one to failures 13 14 Add one to student counter 15 16 Display the number of passes 17 Display the number of failures 18 19 If more than eight students passed 20 Display “Bonus to instructor!” Image Credit: www.bfoit.org
  • 23. Conversion to Class Analysis • Our next program implements the pseudocode. • This example does not contain a class—it contains just a source code file with function main performing all the application’s work. • This source code file contained function main, which created an object of the class and called its member functions. Occasionally, when it does not make sense to try to create a reusable class to demonstrate a concept, we’ll use an example contained entirely within the main function of a single source code file. • The program declares the variables used to process the examination results. We’ve taken advantage of a feature of C++ that allows variable initialization to be incorporated into declarations (passes is initialized to 0, failures is initialized to 0 and studentCounter is initialized to 1). Image Credit: www.freshideawebsites.com2
  • 24. Conversion to Class Analysis • The while statement in the program loops 10 times. Each iteration inputs and processes one exam result. • The if…else statement for processing each result is nested in the while statement. If the result is 1, the if…else statement increments passes; otherwise, it assumes the result is 2 and increments failures. • The program increments studentCounter before the loop condition is tested again. After 10 values have been input, the loop terminates and the program displays the number of passes and the number of failures. • The if statement in determines whether more than eight students passed the exam and, if so, outputs the message "Bonus to instructor!". Image Credit: www.youronlinesuccess.com.au
  • 26. Assignment Operators • C++ provides several assignment operators for abbreviating assignment expressions. • For example, the statement: can be abbreviated with the addition assignment operator += as: which adds the value of the expression on the operator’s right to the value of the variable on the operator’s left and stores the result in the left-side variable. c = c + 3; c += 3; Image Credit: www.wpclipart.com
  • 27. Assignment Operators • Any statement of the form: in which the same variable appears on both sides of the assignment operator and operator is one of the binary operators +, -, *, /, or %, can be written in the form: variable = variable operator expression; variable operator= expression;
  • 28. Increment and Decrement Operators • In addition to the arithmetic assignment operators, C++ also provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable. • These are the unary increment operator, ++, and the unary decrement operator, --. • A program can increment by 1 the value of a variable called c using the increment operator, ++, rather than the expression c = c + 1 or c += 1. • An increment or decrement operator that’s prefixed to (placed before) a variable is referred to as the prefix increment or prefix decrement operator, respectively. • An increment or decrement operator that’s postfixed to (placed after) a variable is referred to as the postfix increment or postfix decrement operator, respectively. Image Credit: www.property118.com
  • 29. Software Engineering Tips! • Unlike binary operators, the unary increment and decrement operators should be placed next to their operands, with no intervening spaces. • Attempting to use the increment or decrement operator on an expression other than a modifiable variable name or reference, e.g., writing ++(x + 1), is a syntax error.
  • 32. What We Covered Today 1. 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. 2. 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/
  • 33. What’s In Your C++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline While
  • 34. 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/
  • 35. An Introduction To Software Development Using C++ Class #3: Variables, Math
  • 36. Homework #2: A Smarter Stoplight Problem • Smallville is basically happy with the 4-way signal control system that you designed for them. However, now they want to make some changes: – The lights in your system need to change color based primarily on the passage of time. – Change your program so that green lights last for 12 seconds, yellow lights last for 3 seconds and red lights last until the light turns green again. – Priority support for Smallville emergency vehicles needs to be added. – Run the program for 60 seconds. – At 35 seconds into the simulation, simulate an emergency vehicle approaching the East traffic light. – At 45 seconds simulate the emergency vehicle moving on and the system returning to normal. • Rules – You must modify Dr. Anderson's solution to HW #1 to create your solution to this homework. – You must use a class in your solution. – You must declare at least 4 objects in your solution.
  • 37. How To Make Really, Really Long IF Statements: Logical Operators • The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. • The logical operators && and || are used when evaluating two expressions to obtain a single relational result. • The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. • The operator || corresponds to the Boolean logical operation OR, which yields true if either of its operands is true, thus being false only when both operands are false. • When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. This is known as short-circuit evaluation Image Credit: www.linkedin.com
  • 39. Today’s In-Class C++ Programming Assignment • Develop a C++ program that will determine if a department store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available: a) Account number (an integer) b) Balance at the beginning of the month c) Total of all items charged by this customer this month d) Total of all credits applied to this customer's account this month e) Allowed credit limit • The program should input each of these facts, calculate the new balance (= beginning balance + charges – credits) and determine if the new balance exceeds the customer's credit limit. For those customers whose credit limit is exceeded, the program should display the customer's account number, credit limit, new balance and the message “Credit limit exceeded”. Image Credit:: www.accpc.com
  • 40. What Should This Program Look Like?
  • 41. Answer To Today’s Challenge // In-Class Exercise #6 - Credit Card #include <iostream> using std::cout; using std::endl; using std::cin; #include <iomanip> int main() { int accountNumber; double balance, charges, credits, limit; cout << "Enter account number (-1 to end): "; cin >> accountNumber; while ( accountNumber != -1 ) { cout << "Enter beginning balance: "; cin >> balance; cout << "Enter total charges: "; cin >> charges; cout << "Enter total credits: "; cin >> credits; cout << "Enter credit limit: "; cin >> limit; balance += charges - credits; if ( balance > limit ) cout << "Account: " << accountNumber << "nCredit limit: " << limit << "nBalance: " << balance << "nCredit Limit Exceeded.n"; cout << "nEnter account number (-1 to end): "; cin >> accountNumber; } cout << endl; // ensure all output is displayed return 0; } Image Creditigoglobal.org
  • 42. What We Covered Today 1. An introduction to keeping track of credit card payments. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 43. What We’ll Be Covering Next Time 1. Palindromes Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

Editor's Notes

  1. 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.
  2. 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.