SlideShare uma empresa Scribd logo
1 de 48
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++
Eighth Edition
Chapter 3:
Variables and Constants
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Distinguish among a variable, a named constant, and a
literal constant
• Explain how data is stored in memory
• Select an appropriate name, data type, and initial value
for a memory location
• Declare a memory location in C++
An Introduction to Programming with C++, Eighth Edition
Chapter Objectives
2
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• After Step 3, programmer has an algorithm and has
desk-checked it
• The fourth step in the process is coding the algorithm
into a program
• The step begins by assigning a descriptive name, data
type, and (optionally) initial value to each unique input,
processing, and output item in the IPO chart
• These are used to store the item in the computer’s
internal memory
An Introduction to Programming with C++, Eighth Edition
Beginning Step 4 in the Problem-Solving
Process
3
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Computer’s internal memory is composed of memory
locations, each with a unique numeric address
• Similar to collection of storage bins
• Each address can store one item at a time
• Address can contain numbers, text, or program
instructions
• To use a memory location, programmer must reserve
the address, called declaring
An Introduction to Programming with C++, Eighth Edition
Internal Memory
4
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Declaring a memory location is done with an instruction
that assigns a name, data type, and (optional) initial
value
• The name allows the programmer to refer to the
memory location elsewhere in the program using a
descriptive word, rather than the numeric address
• The data type indicates what type of information the
address will store (e.g., number or text)
An Introduction to Programming with C++, Eighth Edition
Internal Memory (cont’d.)
5
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Two types of memory locations can be declared:
variables and named constants
• Variables are memory locations whose values can
change during runtime (when the program is running)
• Most memory locations are variables
• Named constants are memory locations whose values
cannot change during program execution
An Introduction to Programming with C++, Eighth Edition
Internal Memory (cont’d.)
6
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Internal Memory (cont’d.)
Figure 3-1 Illustration of show boxes and memory locations
7
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Name (identifier) assigned to a memory location should
be descriptive
• Should help the programmer/other programmers
remember/understand the memory location’s purpose
• Should be as short as possible while still being
descriptive (especially if referenced often)
• Short names are easier to read and result in more
concise code
An Introduction to Programming with C++, Eighth Edition
Selecting a Name for a Memory Location
8
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Rules for memory location names in C++
– Name must begin with a letter and contain only letters,
numbers, and the underscore character
– No punctuation marks, spaces, or other special
characters (such as $ or %) are allowed
– Cannot be a keyword (word that has special meaning in
C++)
– Names are case sensitive
• Example: discount is different from DISCOUNT and
from Discount
An Introduction to Programming with C++, Eighth Edition
Selecting a Name for a Memory Location
(cont’d.)
9
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Most programmers use uppercase letters for named
constants and lowercase for variables
– Example: PI (constant), radius (variable)
• If constants contain more than one word, separate
words with underscores
– Example: TAX_RATE
• If variables contain more than one word, capitalize the
first letter of each word after the first (called camel
case)
– Example: adjustedGrossIncome
An Introduction to Programming with C++, Eighth Edition
Selecting a Name for a Memory Location
(cont’d.)
10
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Figure 3-2 How to name a memory location in C++
11
Selecting a Name for a Memory Location
(cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Revisiting the Addison O’Reilly Problem
Figure 3-3 Problem specification, IPO chart,
and desk-check table from Chapter 2
12
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• IPO chart contains four input, processing, and output
items
• Four memory locations are needed to store the values
of the items
• Memory locations will be variables since their values
will change during runtime
An Introduction to Programming with C++, Eighth Edition
Revisiting the Addison O’Reilly Problem
(cont’d.)
13
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Revisiting the Addison O’Reilly Problem
(cont’d.)
Figure 3-4 Names of the variables for the Addision O’Reilly problem
14
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Memory locations come in different types and sizes
• Type and size you choose depends on the item you
want to store
• A memory location will only accept an item that
matches its data type
• Data type of a memory location is determined by the
programmer when declaring the location
An Introduction to Programming with C++, Eighth Edition
Selecting a Data Type for a Memory
Location
15
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Fundamental data types are basic data types built into
C++
– Also called primitive or built-in data types
– Include short, int, float, double, bool, and
char
• bool data type stores Boolean values (true and false)
• short and int types store integers (numbers without
a decimal place)
– Differences are range of values and memory used (int
has the greater of both)
An Introduction to Programming with C++, Eighth Edition
Selecting a Data Type for a Memory
Location (cont’d.)
16
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• float and double types store real numbers
(numbers with a decimal place)
– Differences are range of values, precision, and memory
used (double has the greater of each)
• char type stores characters (letter, symbol, or number
that will not be used in a calculation)
– Only one character stored at a time
• string data type is a user-defined data type (defined
with a class, or group of instructions)
– Can store zero or more characters
An Introduction to Programming with C++, Eighth Edition
Selecting a Data Type for a Memory
Location (cont’d.)
17
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Selecting a Data Type for a Memory
Location (cont’d.)
Figure 3-5 Most commonly used data types in C++
18
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Selecting a Data Type for a Memory
Location (cont’d.)
Figure 3-6 Data type assigned to each
variable for the Addison O’Reilly problem
19
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Numbers represented in internal memory using binary
(base 2) number system (two digits, 0 and 1)
• We are used to the decimal (base 10) number system
(ten digits, 0 through 9)
• Character data is stored using ASCII codes
– Eight-bit codes (bit = binary digit, 0 or 1)
– Upper- and lowercase versions of letters have distinct
codes
• Computer distinguishes between numbers and ASCII
codes based on data type
An Introduction to Programming with C++, Eighth Edition
How Data Is Stored in Internal Memory
20
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
How Data Is Stored in Internal Memory
(cont’d.)
Figure 3-7 How to use the decimal (base 10) number system
21
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
How Data Is Stored in Internal Memory
(cont’d.)
Figure 3-8 How to use the binary (base 2) number system
22
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Figure 3-9 Partial ASCII chart
23
How Data Is Stored in Internal Memory
(cont’d.)
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Setting an initial value for a variable or named constant
is called initializing
• Required for constants; recommended for variables
• Memory locations are usually initialized with a literal
constant (item of data that can appear in a program
instruction and be stored in memory)
• Data type of literal constant should match data type of
memory location it is assigned to
An Introduction to Programming with C++, Eighth Edition
Selecting an Initial Value for a Memory
Location
24
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Numeric literal constants initialize short, int, float,
and double data types
– Can contain digits 0 through 9, +, -, ., and e or E (for
scientific notation)
• Character literal constants initialize char data types
– Consist of one character in single quotation marks
• String literal constants initialize string data types
– Zero or more characters enclosed in double quotation
marks
– Empty string (“”) is a valid string literal constant
An Introduction to Programming with C++, Eighth Edition
Selecting an Initial Value for a Memory
Location (cont’d.)
25
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Before assigning initial value to a memory location,
computer checks that value’s data type matches
location’s data type
• If they don’t match, computer performs implicit type
conversion to match them
– If initial value is converted to type that holds larger
numbers, value is promoted
– If initial value is converted to type that only holds smaller
numbers, value is demoted
• Promoting will not usually have adverse effects, but
demoting can (information is lost)
An Introduction to Programming with C++, Eighth Edition
Selecting an Initial Value for a Memory
Location (cont’d.)
26
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Important to initialize memory locations with values of
the same data type
• Named constants should be initialized with the value
they will hold for the duration of the program
• Variables whose initial values are not known should still
be initialized
– short and int types usually initialized to 0
– float and double types usually initialized to 0.0
– string types usually initialized to empty string (“”)
– bool types initialized to either true or false
An Introduction to Programming with C++, Eighth Edition
Selecting an Initial Value for a Memory
Location (cont’d.)
27
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Selecting an Initial Value for a Memory
Location (cont’d.)
Figure 3-11 Initial values for the variables
in the Addison O’Reilly problem
28
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Variables and named constants are declared using a
statement (C++ instruction)
• A statement that declares a variable causes the
computer to set aside a memory location with the given
name, data type, and initial value
• Statements must follow correct syntax (rules of a
programming language)
• In C++, all statements must end with a semicolon
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location
29
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• When declaring variables, a data type and name must
be provided
• Syntax for declaring a variable in C++
– dataType variableName [= initialValue];
• After variable is declared, you use its name to refer to it
later in the program
• Initial value is optional but recommended
• If variable is not initialized, it contains the previous
value of that memory location, which may be the wrong
type (called a garbage value)
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
30
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Syntax for declaring a named constant in C++
– const dataType constantName = value;
• The const keyword indicates that the memory location
is a named constant (value cannot be changed during
runtime)
• Initial value required for constants, unlike variables
• As with variables, after declaring a constant, you can
use its name to refer to it later in the program
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
31
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Several advantages to using named constants when
appropriate
– Make program more self-documenting (meaningful words
in place of numbers)
– Value cannot be inadvertently changed during runtime
– Typing a name is less error-prone than a long number
– Mistyping a constant’s name will trigger a compiler error;
mistyping a number will not
– If the constant needs to be changed when modifying the
program, it only needs to be changed in one place
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
32
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
Figure 3-12 How to declare a variable in C++
33
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
Figure 3-13 C++ declaration statements for the
variables in the Addision O’Reilly problem
34
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Declaring a Memory Location (cont’d.)
Figure 3-14 How to declare a named constant in C++
35
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Fourth step in problem-solving process is coding the
algorithm
• Memory location is declared for each input, processing,
and output item in IPO chart
• Numeric data is stored in computer’s internal memory
using binary number system
• Memory locations store one item at a time
• Memory location’s data type determines how a value is
stored and interpreted when retrieved
An Introduction to Programming with C++, Eighth Edition
Summary
36
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Two types of memory locations: variables and named
constants
• Memory locations are declared using a statement that
assigns a name, data type, and initial value
• Initial value required for named constants but optional
for variables (though recommended)
• Most memory locations initialized with literal constants,
except bool (initialized with keywords true or
false)
An Introduction to Programming with C++, Eighth Edition
Summary (cont’d.)
37
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Data type of literal constant assigned to memory
location should be same as memory location’s type
• If types don’t match, implicit type conversion is used to
either promote or demote so they match
• Promoting doesn’t usually cause problems, but
demoting can
• Syntax for declaring variables
– dataType variableName [= initialValue];
• Syntax for declaring named constants
– const dataType constantName = value;
An Introduction to Programming with C++, Eighth Edition
Summary (cont’d.)
38
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
Study the IPO chart shown in Figure 3-15 on page 64
and answer the questions below.
• How many memory locations will the problem require?
• How many of the memory locations will be variables,
and how many will be named constants? Why did you
choose one over the other?
• How would you write the appropriate declaration
statements? Use the int data type for the quantity sold,
and the double data type for the remaining items.
An Introduction to Programming with C++, Eighth Edition
Lab 3-1: Stop and Analyze
39
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Lab 3-2: Plan and Create
Figure 3-16 Problem specification for Lab 3-2
40
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Lab 3-2: Plan and Create (cont’d.)
Figure 3-17 Partially completed IPO chart showing input and output items
41
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Lab 3-2: Plan and Create (cont’d.)
Figure 3-18 Completed IPO chart for Lab 3-2
42
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Lab 3-2: Plan and Create (cont’d.)
Figure 3-20 Completed desk-check table for Lab 3-2
43
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
An Introduction to Programming with C++, Eighth Edition
Lab 3-2: Plan and Create (cont’d.)
Figure 3-21 IPO chart information and C++ instructions for Lab 3-2
44
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
Modify the IPO chart in Figure 3-18 so that it allows the
user to enter the commission rate. Then make the
appropriate modifications to Figure 3-21.
An Introduction to Programming with C++, Eighth Edition
Lab 3-3: Modify
Figure 3-18 Completed IPO chart for Lab 3-2
45
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
Professor Merrita wants a program that calculates and
displays the volume of a cylinder, given the cylinder’s
radius (r) and height (h). Given the items listed below in
Figure 3-22, create a complete IPO chart similar to
Figure 3-21 for the problem.
An Introduction to Programming with C++, Eighth Edition
Lab 3-4: What’s Missing?
Figure 3-22 Items and statements for Lab 3-4
46
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
After creating an appropriate algorithm for Lab 3-4, desk-
check it twice. Use 9 and 6 as the height and radius fro
the first desk-check, then use 17 and 15.
An Introduction to Programming with C++, Eighth Edition
Lab 3-5: Desk-Check
47
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in
whole or in part.
• Correct the C++ instructions shown in Figure 3-23
– The memory locations will store real numbers
An Introduction to Programming with C++, Eighth Edition
Lab 3-6: Debug
Figure 3-23 IPO chart information and C++ instructions for Lab 3-6
48

Mais conteúdo relacionado

Mais procurados

Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variablessangrampatil81
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures topu93
 
Computer Networks Unit 1 Introduction and Physical Layer
Computer Networks Unit 1 Introduction and Physical Layer Computer Networks Unit 1 Introduction and Physical Layer
Computer Networks Unit 1 Introduction and Physical Layer Dr. SELVAGANESAN S
 
Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Kamran Zafar
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programmingChitrank Dixit
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Md. Imran Hossain Showrov
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Types of instructions
Types of instructionsTypes of instructions
Types of instructionsihsanjamil
 
BASIC COMPUTER ORGANIZATION AND DESIGN
BASIC  COMPUTER  ORGANIZATION  AND  DESIGNBASIC  COMPUTER  ORGANIZATION  AND  DESIGN
BASIC COMPUTER ORGANIZATION AND DESIGNDr. Ajay Kumar Singh
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 

Mais procurados (20)

Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Demand paging
Demand pagingDemand paging
Demand paging
 
Computer Networks Unit 1 Introduction and Physical Layer
Computer Networks Unit 1 Introduction and Physical Layer Computer Networks Unit 1 Introduction and Physical Layer
Computer Networks Unit 1 Introduction and Physical Layer
 
Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)Lecture 1 programming fundamentals (PF)
Lecture 1 programming fundamentals (PF)
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
C pointer
C pointerC pointer
C pointer
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Diff between c and c++
Diff between c and c++Diff between c and c++
Diff between c and c++
 
C vs c++
C vs c++C vs c++
C vs c++
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
C Language
C LanguageC Language
C Language
 
Types of instructions
Types of instructionsTypes of instructions
Types of instructions
 
BASIC COMPUTER ORGANIZATION AND DESIGN
BASIC  COMPUTER  ORGANIZATION  AND  DESIGNBASIC  COMPUTER  ORGANIZATION  AND  DESIGN
BASIC COMPUTER ORGANIZATION AND DESIGN
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 

Semelhante a Chapter 3 - Variables and Constants

Chapter 9 Value-Returning Functions
Chapter 9 Value-Returning FunctionsChapter 9 Value-Returning Functions
Chapter 9 Value-Returning Functionsmshellman
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
Chapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition StructureChapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition Structuremshellman
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++Vaibhav Khanna
 
Choose any multi-national organization that you would like to use .docx
Choose any multi-national organization that you would like to use .docxChoose any multi-national organization that you would like to use .docx
Choose any multi-national organization that you would like to use .docxchristinemaritza
 
DC16_Ch06 (1).pptx
DC16_Ch06 (1).pptxDC16_Ch06 (1).pptx
DC16_Ch06 (1).pptxAiman Niazi
 
computer technology-computing components
computer technology-computing componentscomputer technology-computing components
computer technology-computing componentsHammadBhatti20
 
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docxsleeperharwell
 

Semelhante a Chapter 3 - Variables and Constants (20)

Lesson 9.2 guessing the game program
Lesson 9.2 guessing the game programLesson 9.2 guessing the game program
Lesson 9.2 guessing the game program
 
Lesson 3.1 variables and constant
Lesson 3.1 variables and constantLesson 3.1 variables and constant
Lesson 3.1 variables and constant
 
Lesson 6.2 logic error
Lesson  6.2 logic errorLesson  6.2 logic error
Lesson 6.2 logic error
 
Lesson 6.1 more on selection structure
Lesson 6.1 more on selection structureLesson 6.1 more on selection structure
Lesson 6.1 more on selection structure
 
Lesson 1 introduction to programming
Lesson 1 introduction to programmingLesson 1 introduction to programming
Lesson 1 introduction to programming
 
Chapter 9 Value-Returning Functions
Chapter 9 Value-Returning FunctionsChapter 9 Value-Returning Functions
Chapter 9 Value-Returning Functions
 
Lesson 9.1 value returning
Lesson 9.1 value returningLesson 9.1 value returning
Lesson 9.1 value returning
 
Sql9e ppt ch08
Sql9e ppt ch08Sql9e ppt ch08
Sql9e ppt ch08
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
Chapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition StructureChapter 8 - More on the Repetition Structure
Chapter 8 - More on the Repetition Structure
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Lesson 8 more on repitition structure
Lesson 8 more on repitition structureLesson 8 more on repitition structure
Lesson 8 more on repitition structure
 
Lesson 7.1 repitition structure
Lesson 7.1 repitition structureLesson 7.1 repitition structure
Lesson 7.1 repitition structure
 
DC16_Ch06.pptx
DC16_Ch06.pptxDC16_Ch06.pptx
DC16_Ch06.pptx
 
Object oriented programming 7 first steps in oop using c++
Object oriented programming 7 first steps in oop using  c++Object oriented programming 7 first steps in oop using  c++
Object oriented programming 7 first steps in oop using c++
 
Choose any multi-national organization that you would like to use .docx
Choose any multi-national organization that you would like to use .docxChoose any multi-national organization that you would like to use .docx
Choose any multi-national organization that you would like to use .docx
 
DC16_Ch06 (1).pptx
DC16_Ch06 (1).pptxDC16_Ch06 (1).pptx
DC16_Ch06 (1).pptx
 
Chapter 03.ppt
Chapter 03.pptChapter 03.ppt
Chapter 03.ppt
 
computer technology-computing components
computer technology-computing componentscomputer technology-computing components
computer technology-computing components
 
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
9781337117562_ppt_ch01.pptxChapter 1An Overview of Compute.docx
 

Último

Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Último (20)

Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Chapter 3 - Variables and Constants

  • 1. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++ Eighth Edition Chapter 3: Variables and Constants
  • 2. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Distinguish among a variable, a named constant, and a literal constant • Explain how data is stored in memory • Select an appropriate name, data type, and initial value for a memory location • Declare a memory location in C++ An Introduction to Programming with C++, Eighth Edition Chapter Objectives 2
  • 3. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • After Step 3, programmer has an algorithm and has desk-checked it • The fourth step in the process is coding the algorithm into a program • The step begins by assigning a descriptive name, data type, and (optionally) initial value to each unique input, processing, and output item in the IPO chart • These are used to store the item in the computer’s internal memory An Introduction to Programming with C++, Eighth Edition Beginning Step 4 in the Problem-Solving Process 3
  • 4. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Computer’s internal memory is composed of memory locations, each with a unique numeric address • Similar to collection of storage bins • Each address can store one item at a time • Address can contain numbers, text, or program instructions • To use a memory location, programmer must reserve the address, called declaring An Introduction to Programming with C++, Eighth Edition Internal Memory 4
  • 5. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Declaring a memory location is done with an instruction that assigns a name, data type, and (optional) initial value • The name allows the programmer to refer to the memory location elsewhere in the program using a descriptive word, rather than the numeric address • The data type indicates what type of information the address will store (e.g., number or text) An Introduction to Programming with C++, Eighth Edition Internal Memory (cont’d.) 5
  • 6. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Two types of memory locations can be declared: variables and named constants • Variables are memory locations whose values can change during runtime (when the program is running) • Most memory locations are variables • Named constants are memory locations whose values cannot change during program execution An Introduction to Programming with C++, Eighth Edition Internal Memory (cont’d.) 6
  • 7. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Internal Memory (cont’d.) Figure 3-1 Illustration of show boxes and memory locations 7
  • 8. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Name (identifier) assigned to a memory location should be descriptive • Should help the programmer/other programmers remember/understand the memory location’s purpose • Should be as short as possible while still being descriptive (especially if referenced often) • Short names are easier to read and result in more concise code An Introduction to Programming with C++, Eighth Edition Selecting a Name for a Memory Location 8
  • 9. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Rules for memory location names in C++ – Name must begin with a letter and contain only letters, numbers, and the underscore character – No punctuation marks, spaces, or other special characters (such as $ or %) are allowed – Cannot be a keyword (word that has special meaning in C++) – Names are case sensitive • Example: discount is different from DISCOUNT and from Discount An Introduction to Programming with C++, Eighth Edition Selecting a Name for a Memory Location (cont’d.) 9
  • 10. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Most programmers use uppercase letters for named constants and lowercase for variables – Example: PI (constant), radius (variable) • If constants contain more than one word, separate words with underscores – Example: TAX_RATE • If variables contain more than one word, capitalize the first letter of each word after the first (called camel case) – Example: adjustedGrossIncome An Introduction to Programming with C++, Eighth Edition Selecting a Name for a Memory Location (cont’d.) 10
  • 11. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Figure 3-2 How to name a memory location in C++ 11 Selecting a Name for a Memory Location (cont’d.)
  • 12. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Revisiting the Addison O’Reilly Problem Figure 3-3 Problem specification, IPO chart, and desk-check table from Chapter 2 12
  • 13. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • IPO chart contains four input, processing, and output items • Four memory locations are needed to store the values of the items • Memory locations will be variables since their values will change during runtime An Introduction to Programming with C++, Eighth Edition Revisiting the Addison O’Reilly Problem (cont’d.) 13
  • 14. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Revisiting the Addison O’Reilly Problem (cont’d.) Figure 3-4 Names of the variables for the Addision O’Reilly problem 14
  • 15. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Memory locations come in different types and sizes • Type and size you choose depends on the item you want to store • A memory location will only accept an item that matches its data type • Data type of a memory location is determined by the programmer when declaring the location An Introduction to Programming with C++, Eighth Edition Selecting a Data Type for a Memory Location 15
  • 16. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Fundamental data types are basic data types built into C++ – Also called primitive or built-in data types – Include short, int, float, double, bool, and char • bool data type stores Boolean values (true and false) • short and int types store integers (numbers without a decimal place) – Differences are range of values and memory used (int has the greater of both) An Introduction to Programming with C++, Eighth Edition Selecting a Data Type for a Memory Location (cont’d.) 16
  • 17. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • float and double types store real numbers (numbers with a decimal place) – Differences are range of values, precision, and memory used (double has the greater of each) • char type stores characters (letter, symbol, or number that will not be used in a calculation) – Only one character stored at a time • string data type is a user-defined data type (defined with a class, or group of instructions) – Can store zero or more characters An Introduction to Programming with C++, Eighth Edition Selecting a Data Type for a Memory Location (cont’d.) 17
  • 18. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Selecting a Data Type for a Memory Location (cont’d.) Figure 3-5 Most commonly used data types in C++ 18
  • 19. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Selecting a Data Type for a Memory Location (cont’d.) Figure 3-6 Data type assigned to each variable for the Addison O’Reilly problem 19
  • 20. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Numbers represented in internal memory using binary (base 2) number system (two digits, 0 and 1) • We are used to the decimal (base 10) number system (ten digits, 0 through 9) • Character data is stored using ASCII codes – Eight-bit codes (bit = binary digit, 0 or 1) – Upper- and lowercase versions of letters have distinct codes • Computer distinguishes between numbers and ASCII codes based on data type An Introduction to Programming with C++, Eighth Edition How Data Is Stored in Internal Memory 20
  • 21. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition How Data Is Stored in Internal Memory (cont’d.) Figure 3-7 How to use the decimal (base 10) number system 21
  • 22. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition How Data Is Stored in Internal Memory (cont’d.) Figure 3-8 How to use the binary (base 2) number system 22
  • 23. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Figure 3-9 Partial ASCII chart 23 How Data Is Stored in Internal Memory (cont’d.)
  • 24. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Setting an initial value for a variable or named constant is called initializing • Required for constants; recommended for variables • Memory locations are usually initialized with a literal constant (item of data that can appear in a program instruction and be stored in memory) • Data type of literal constant should match data type of memory location it is assigned to An Introduction to Programming with C++, Eighth Edition Selecting an Initial Value for a Memory Location 24
  • 25. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Numeric literal constants initialize short, int, float, and double data types – Can contain digits 0 through 9, +, -, ., and e or E (for scientific notation) • Character literal constants initialize char data types – Consist of one character in single quotation marks • String literal constants initialize string data types – Zero or more characters enclosed in double quotation marks – Empty string (“”) is a valid string literal constant An Introduction to Programming with C++, Eighth Edition Selecting an Initial Value for a Memory Location (cont’d.) 25
  • 26. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Before assigning initial value to a memory location, computer checks that value’s data type matches location’s data type • If they don’t match, computer performs implicit type conversion to match them – If initial value is converted to type that holds larger numbers, value is promoted – If initial value is converted to type that only holds smaller numbers, value is demoted • Promoting will not usually have adverse effects, but demoting can (information is lost) An Introduction to Programming with C++, Eighth Edition Selecting an Initial Value for a Memory Location (cont’d.) 26
  • 27. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Important to initialize memory locations with values of the same data type • Named constants should be initialized with the value they will hold for the duration of the program • Variables whose initial values are not known should still be initialized – short and int types usually initialized to 0 – float and double types usually initialized to 0.0 – string types usually initialized to empty string (“”) – bool types initialized to either true or false An Introduction to Programming with C++, Eighth Edition Selecting an Initial Value for a Memory Location (cont’d.) 27
  • 28. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Selecting an Initial Value for a Memory Location (cont’d.) Figure 3-11 Initial values for the variables in the Addison O’Reilly problem 28
  • 29. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Variables and named constants are declared using a statement (C++ instruction) • A statement that declares a variable causes the computer to set aside a memory location with the given name, data type, and initial value • Statements must follow correct syntax (rules of a programming language) • In C++, all statements must end with a semicolon An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location 29
  • 30. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • When declaring variables, a data type and name must be provided • Syntax for declaring a variable in C++ – dataType variableName [= initialValue]; • After variable is declared, you use its name to refer to it later in the program • Initial value is optional but recommended • If variable is not initialized, it contains the previous value of that memory location, which may be the wrong type (called a garbage value) An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) 30
  • 31. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Syntax for declaring a named constant in C++ – const dataType constantName = value; • The const keyword indicates that the memory location is a named constant (value cannot be changed during runtime) • Initial value required for constants, unlike variables • As with variables, after declaring a constant, you can use its name to refer to it later in the program An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) 31
  • 32. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Several advantages to using named constants when appropriate – Make program more self-documenting (meaningful words in place of numbers) – Value cannot be inadvertently changed during runtime – Typing a name is less error-prone than a long number – Mistyping a constant’s name will trigger a compiler error; mistyping a number will not – If the constant needs to be changed when modifying the program, it only needs to be changed in one place An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) 32
  • 33. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) Figure 3-12 How to declare a variable in C++ 33
  • 34. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) Figure 3-13 C++ declaration statements for the variables in the Addision O’Reilly problem 34
  • 35. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Declaring a Memory Location (cont’d.) Figure 3-14 How to declare a named constant in C++ 35
  • 36. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Fourth step in problem-solving process is coding the algorithm • Memory location is declared for each input, processing, and output item in IPO chart • Numeric data is stored in computer’s internal memory using binary number system • Memory locations store one item at a time • Memory location’s data type determines how a value is stored and interpreted when retrieved An Introduction to Programming with C++, Eighth Edition Summary 36
  • 37. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Two types of memory locations: variables and named constants • Memory locations are declared using a statement that assigns a name, data type, and initial value • Initial value required for named constants but optional for variables (though recommended) • Most memory locations initialized with literal constants, except bool (initialized with keywords true or false) An Introduction to Programming with C++, Eighth Edition Summary (cont’d.) 37
  • 38. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Data type of literal constant assigned to memory location should be same as memory location’s type • If types don’t match, implicit type conversion is used to either promote or demote so they match • Promoting doesn’t usually cause problems, but demoting can • Syntax for declaring variables – dataType variableName [= initialValue]; • Syntax for declaring named constants – const dataType constantName = value; An Introduction to Programming with C++, Eighth Edition Summary (cont’d.) 38
  • 39. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Study the IPO chart shown in Figure 3-15 on page 64 and answer the questions below. • How many memory locations will the problem require? • How many of the memory locations will be variables, and how many will be named constants? Why did you choose one over the other? • How would you write the appropriate declaration statements? Use the int data type for the quantity sold, and the double data type for the remaining items. An Introduction to Programming with C++, Eighth Edition Lab 3-1: Stop and Analyze 39
  • 40. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Lab 3-2: Plan and Create Figure 3-16 Problem specification for Lab 3-2 40
  • 41. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Lab 3-2: Plan and Create (cont’d.) Figure 3-17 Partially completed IPO chart showing input and output items 41
  • 42. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Lab 3-2: Plan and Create (cont’d.) Figure 3-18 Completed IPO chart for Lab 3-2 42
  • 43. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Lab 3-2: Plan and Create (cont’d.) Figure 3-20 Completed desk-check table for Lab 3-2 43
  • 44. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. An Introduction to Programming with C++, Eighth Edition Lab 3-2: Plan and Create (cont’d.) Figure 3-21 IPO chart information and C++ instructions for Lab 3-2 44
  • 45. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Modify the IPO chart in Figure 3-18 so that it allows the user to enter the commission rate. Then make the appropriate modifications to Figure 3-21. An Introduction to Programming with C++, Eighth Edition Lab 3-3: Modify Figure 3-18 Completed IPO chart for Lab 3-2 45
  • 46. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Professor Merrita wants a program that calculates and displays the volume of a cylinder, given the cylinder’s radius (r) and height (h). Given the items listed below in Figure 3-22, create a complete IPO chart similar to Figure 3-21 for the problem. An Introduction to Programming with C++, Eighth Edition Lab 3-4: What’s Missing? Figure 3-22 Items and statements for Lab 3-4 46
  • 47. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. After creating an appropriate algorithm for Lab 3-4, desk- check it twice. Use 9 and 6 as the height and radius fro the first desk-check, then use 17 and 15. An Introduction to Programming with C++, Eighth Edition Lab 3-5: Desk-Check 47
  • 48. © 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. • Correct the C++ instructions shown in Figure 3-23 – The memory locations will store real numbers An Introduction to Programming with C++, Eighth Edition Lab 3-6: Debug Figure 3-23 IPO chart information and C++ instructions for Lab 3-6 48