Using Variables and
Performing Calculations
Variables hold values in memory so a program can manipulate them. Different kinds of variables
hold different types of data: numbers, text, pictures, Halo scores, even complex groups of data
such as employee records.
In this lesson you learn what variables are and how to use them. You learn how to define
variables, put data in them, and use them to perform simple calculations.
WHAT ARE VARIABLES?
Technically speaking a variable is a named piece of memory that can hold some data of a specific
type. For example, a program might allocate 4 bytes of memory to store an integer. You might
name those bytes “payoffs” so you can easily refer to them in the programs code.
Less technically, you can think of a variable as a named place to put a piece of data. The
program’s code can use the variables to store values and perform calculations. For example,
a program might store two values in variables, add the values together, and store the result
in a third variable.
DATA TYPES
Every variable has a particular data type that determines the kind of data that it can hold. In
general, you cannot place data of one type in a variable of another. For example, if
price is a
variable that can hold a number in dollars and cents, you cannot put the string “Hello” in it.
If you like, you can think of a variable as an envelope (with a name written on the outside)
that can hold some data, but each type of data requires a different shaped envelope. Integers
need relatively small envelopes, singles (which hold numbers with decimal points) need enve-
lopes that are long and thin, and strings need big fat envelopes.
11
596906c11.indd 127 4/7/10 12:32:30 PM
128
LESSON 11 Using Variables and Performing CalCUlations
BITS AND BYTES
A bit is a single binary digit of memory that can have the value 0 or 1. (The name
“bit” comes from “BInary digiT.” Or is it “Binary digIT?”) Generally, bits are
grouped into bytes and a program doesn’t work with bits directly.
A byte is a chunk of memory holding 8 bits. If you view the bits as digits in a
binary number, then a byte can hold values between 0 (00000000 in binary) and
255 (11111111 in binary). Groups of bytes make up larger data types such as inte-
gers and strings.
A nibble is half a byte. Way back in the old days when memory was expensive and
computers filled warehouses instead of laps, some programs needed to split bytes
and consider the nibbles separately to save space. Now that memory is as cheap as
day-old lottery tickets, the nibble is a historical curiosity.
Bigger units of memory include kilobyte (KB) = 1,024 bytes, megabyte (MB) =
1,024KB, gigabyte (GB) = 1,024MB, and terabyte (TB) = 1,024GB. These are often
used to measure the size of files, computer memory, flash drives, and disk drives.
(Although in some contexts people use powers of 1,000 instead of 1,024. For
example, most disk drive manufacturers define a gigabyte as 1,000,000,000 bytes.)
Sometimes the line between two data types is a bit fuzzy. For example, if a variable should hold a
number, you cannot put in the string “ten.” The fact that “ten” is a number is obvious to a human
but not to a C# program.
You cant even place a string containing the characters “10” in a variable that holds a number.
Though it should be obvious to just about anyone that “10” is a number, C# just knows it’s a string
containing two characters 1 and 0, and doesn’t try to determine that the characters in the string rep-
resent a number.
Programs often need to convert a value from one data type to another (particularly switching between
strings and numbers) so C# provides an assortment of data conversion functions to do just that. The
section “Type Conversions” later in this lesson describes these functions.
Table 11-1 summarizes C#’s built-in data types. The signed types can store values that are positive
or negative while the unsigned types can hold only positive values.
TABLE 111
DATA TYPE MEANING RANGE
byte
Byte 0 to 255
sbyte
Signed byte –128 to 127
short
Small signed integer –32,768 to 32,767
ushort
Unsigned short 0 to 65,535
596906c11.indd 128 4/7/10 12:32:30 PM
Data Types
129
DATA TYPE MEANING RANGE
int
Integer –2,147,483,648 to 2,147,483,647
uint
Unsigned integer 0 to 4,294,967,295
long
Long integer –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong
Unsigned long 0 to 18,446,744,073,709,551,615
float
Floating point Roughly –3.4e38 to 3.4e38
double
Big floating point Roughly –1.8e308 to 1.8e308
decimal
Higher precision and smaller
range than floating-point types
See the following section, “Float, Double,
and Decimal Data Types.”
char
Character A single Unicode character. (Unicode
characters use 16 bits to hold data for
text in scripts such as Arabic, Cyrillic,
Greek, and Thai.)
string
Text A string of Unicode characters.
bool
Boolean Can be true or false.
object
An object Can point to almost anything.
Some of these data types are a bit confusing but the most common data types (int, long, float,
double, and string) are fairly straightforward, and they are the focus of most of this lesson.
Before moving on to further details, however, it’s worth spending a little time comparing the
float, double, and decimal data types.
Float, Double, and Decimal Data Types
The computer represents values or every type in binary using bits and bytes, so some values don’t fit
perfectly in a particular data type. In particular, real numbers such as 1/7 dont have exact binary rep-
resentations, so the
float, double, and decimal data types often introduce slight rounding errors.
For example, a
float represents 1/7 as approximately 0.142857149. Usually the fact that this is not
exactly 1/7 isn’t a problem, but once in a while if you compare two float values to see if they are exactly
equal, roundoff errors make them appear different even though they should be the same.
The
decimal data type helps reduce this problem for decimal values such as 1.5 (but not non-decimal
real values such as 1/7) by storing an exact representation of a decimal value. Instead of storing a value
as a binary number the way
float and double do, decimal stores the number’s digits and its exponent
separately as integral data types with no rounding. That lets it hold 28 or 29 significant digits (depend-
ing on the exact value) for numbers between roughly –7.9e28 and 7.9e28.
596906c11.indd 129 4/7/10 12:32:31 PM
130
LESSON 11 Using Variables and Performing CalCUlations
Note that rounding errors can still occur when you combine decimal values. For example, if you
add 1e28 plus 1e–28, the result would have more than the 28 or 29 significant digits that a
decimal
can provide so it rounds off to 1e28.
The moral of the story is that you should always use the decimal data type for values where you
need great accuracy and the values won’t get truly enormous. In particular, you should always use
decimal for currency values. Unless you’re Bill Gates’ much richer uncle, you’ll never get close to the
largest value a
decimal can represent, and the extra precision can prevent rounding errors during
some fairly complex calculations.
Another interesting feature of the decimal type is that, due to the way it stores
its significant digits, it remembers zeros on the right. For example, if you add
the values 1.35 and 1.65 as
floats, you get the value 3. In contrast, if you add
the same values as
decimals, you get 3.00. The decimal result remembers that
you were working with 2 digits to the right of the decimal point so it stores the
result that way, too.
DECLARING VARIABLES
To declare a variable in C# code, give the data type that you want to use followed by the name that
you want to give the variable. For example, the following code creates a variable named
numMistakes.
The variable’s data type is
int so it can hold an integer between –2,147,483,648 and 2,147,483,647.
int numMistakes;
You can use the equals symbol to assign a value to a variable. For example, the following code sets
numMistakes to 1337:
numMistakes = 1337;
As an added convenience, you can declare a variable and give it a value at the same time, as in:
int numMistakes = 1337;
You can declare several variables of the same type all at once by separating them with commas. You
can even initialize them if you like. The following code declares three
float variables named, x, y,
and
z and gives them initial values of 1, 2, and –40, respectively:
float x = 1, y = 2, z = -40;
The program must assign a value to a variable before it tries to read its value.
For example, C# flags the following code as an error because the second line
tries to use
x on the right-hand side of the equals sign to calculate y before x has
been assigned a value.
int x, y;
y = x + 1;
596906c11.indd 130 4/7/10 12:32:31 PM
Literal Values
131
LITERAL VALUES
A literal value is a piece of data stuck right in the code. For example, in the following statement,
numMistakes is a variable and 1337 is a literal integer value:
int numMistakes = 1337;
Usually C# is pretty smart about using the correct data types for literal values. For example, in
the preceding statement C# knows that
numMistakes is an integer and 1337 is an integer, so it can
safely put an integer value in an integer variable.
Sometimes, however, C# gets confused and assumes a literal value has a data type other than the
one you intend. For example, the following code declares a
float variable named napHours and
tries to assign it the value
6.5. Unfortunately, C# thinks 6.5 is a double and a double won’t fit
inside a
float variable so it flags this as an error.
float napHours = 6.5;
In cases such as this one, you can help C# understand what data type a literal has by adding a sufx
character. For example, the
F character in the following code tells C# that it should treat 6.5 as a
float not a double:
float napHours = 6.5F;
Table 11-2 lists C#s data type sufx characters. You can use the sufxes in either lower- or uppercase.
TABLE 112
DATA TYPE SUFFIX
uint
U
long
L
ulong
UL or LU
float
F
double
D
decimal
M
The int data type doesn’t have a literal sufx character. C# assumes a literal that looks like an
integer is an
int, unless its too big, in which case it assumes the value is a long. For example,
it assumes that 2000000000 is an
int because that value will fit in an int. It assumes that
3000000000 is a
long because it’s too big to fit in an int.
The
byte, sbyte, short, and ushort data types also have no literal suffix characters. Fortunately,
you can assign an integer value to these types and C# will use the value correctly, as long as it fits.
596906c11.indd 131 4/7/10 12:32:31 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.12.124