Download Variables

Transcript
I
N
T
R
O
UNIT 3
T
O
P
R
O
G
R
A
M
M
I
N
G
Variables
DPW
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
T
O
P
R
O
G
R
A
M
M
I
N
G
Variables
•
•
Must be one word, no spaces
Most languages do not allow punctuation
characters
• Most languages do not allow the first
character to be a number
• Name
N
a variable
i bl something
thi th
thatt iindicates
di t
what may be stored in it
• Variables
V i bl can b
be ffrom
– User input
– Created
C t d with
ith a sett statement
t t
t
DPW
– Result from calculations
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
T
O
P
R
O
G
R
A
M
M
I
N
G
Variable Declarations
•
A variable declaration includes
– variable
variable’s
s name
– variable’s data type
• Data
D t Types
T
– Integer – stores only whole numbers
– Real
R l – stores whole
h l or d
decimal
i l numbers
b
– String – any series of characters
• Must be declared before they are used
• Should be initialized to some value
Declare Real creditsTaken
DPW
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
T
O
P
R
O
G
R
A
M
M
I
N
G
Numeric Literals
• Unassigned numbers
• A number written without a decimal
point is assumed to be an Integer
p
g
• A number written with a decimal point is
considered to be Real
• If you do assign a type and use the
decimal point incorrectly
incorrectly, an error will
occur
• Many
M
languages
l
d
do allow
ll
an iinteger
t
tto
DPW
be assigned to a real variable
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
T
O
P
R
O
G
R
A
M
M
I
N
G
Integer
g Division
• Dividing two integers will result in a
truncated integer
• For example
p
10/5 = 2
13/5 = 2
• It is not 2.6 because everything after
th d
the
decimal
i l point
i t iis d
dropped
d
• Java, C++, C and Python use integer
division
DPW
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
Named Constants
•
T
O
P
R
O
G
R
A
M
M
I
N
G
A named constant is a name that
represents a value that cannot be
changed
– Makes programs more self
explanatory
– If a change to the value occurs
occurs, it only
has to be modified in one place
Constant Real creditsTaken
•
If a set statement or anyy other command
tries to change the value of a named
DPW
DPW
constant, an error will occur
© Donna Warren
© 2005-2010
I
N
T
R
O
Desk Checking
g
•
T
O
P
R
O
G
R
A
M
M
I
N
G
•
Also called Hand tracing is a simple
debugging process for locating hard
to find errors in a program
I
Involves
l
creating
ti a chart
h t with
ith a
column for each variable, and a row
f each
for
h line
li off code
d
DPW
DPW
© Donna Warren
© 2005-2010
I
N
T
R
O
T
O
P
R
O
G
R
A
M
M
I
N
G
Documenting a Program
•
External documentation
– Normally called a user manual
• Internal documentation
– Also called comments
– Explains how parts of the program
works
// written by /Donna Warren
DPW
DPW
© Donna Warren
© 2005-2010