Objective #1: Understand the different variable data types used
in C++ and how they differ from constants.
- Variables are used to store values in virtually every
computer program.
- Since values can either be whole numbers, decimal numbers, letters
(i.e. characters), or whole words (i.e. string values), you need to
first choose an appropriate data type
when you use a variable. For example, if you want to store coffee in
a container, you would use a styrofoam cup and not a Dixie cup. Otherwise,
you would burn your hands. Likewise, if you want to store chicken soup
in a container, you would use a bowl and not a plate. Otherwise, the
soup would spill off of the edge of the plate.
- Most computer languages have a select number of different
data types.
Sometimes data types are simply called types.
- You must select the proper
data type for each variable
that you use in a program in order to program efficiently.
- this decreases memory (RAM) usage
- this increases the speed of your program
- The following data
types are common in C++ and will be used in this course:
- To store whole numbers in a variable, we use
a variable of the int
data type.
- An int variable
uses 4 bytes of memory.
- An int variable
can store a number as low as -2,147,483,648.
- An int variable can store
a number as high as 2,147,483,647.
- To store decimal numbers in a variable, we
use a variable of the double data type.
- A double variable
uses 8 bytes of memory.
- A double variable
can store a number as low as -1.7 x 10308.
- A double variable
can store a number as high as 1.7 x 10308.
- A double variable
can store a number with up to 15 digits of precision (significant
digits.)
- Even if the textbook uses the float
data type to store decimal numbers and even if a float
is only 4 bytes, you should use the double
data type. You don't have to understand the following discussion
but it may be interesting to some of you. Decimal numbers (aka
floating point numbers) are stored in a binary version of scientific
notation (b * m * 2^e) with one bit (b) allocated to sign, some
bits allocated to the mantissa (m) and the rest to the exponent
(e). Therefore a float may
have less bits allocated for the mantissa than for an int. In
Microsoft Visual C++ 6.0, the mantissa for a float gets 23 bits
when an int gets 31. Also rounding
errors occur when converting real numbers to and from base 2.
This combination sometimes results in a float
that is slightly smaller than the expected value. If that float
is supposed to store an integer, the truncation that results
when it is assigned to an int
often lowers the expected value by 1. Therefore, to avoid this
problem, use a double that
stores 52 bit mantissas.
- To store a letter or a single character (such
as #, $, *, etc.), we use a variable of the char
(pronounced "care") data type.
- A char variable
only uses 1 byte of memory.
- A char variable
can only hold one letter, digit, or character.
- To store a word or phrase (string value), we use
a variable that is a string.
Technically string is not a data type but you can think of it as
a data type in this course. We will study strings
in more detail in Ch. 9.
- There are other data types that are used in C++
but we will not use them too often in this course. These include unsigned
char, short,
unsigned int,
long, and
unsigned long
for whole numbers and float
and long double
for decimal values. The data type bool is useful to store true
and false
values but sometimes we simply use an int
variable with either a 1 value (to represent true)
or a 0 value (to represent false).
Objective #2: Be able to write declaration statements that declare
and initialize variables.
- Variables must be declared before they are used in C++. Get
into the habit of doing this at the top of your program.
Examples of declaration statements with explanatory inline comments:
char grade; //
a students semester grade
int numStudents;
// number of students in our class
double price; //
price of item
string userName;
// user's name
- Variable names are technically known as identifiers
. You can choose your own variable names but you must be careful to
use valid ones. Otherwise, the compiler will be confused and errors
will result. When choosing your variable names:
- do not use keywords that are defined in the programming language
- do not include spaces or other disallowed characters
- do not use more than 31 characters
- begin the identifier with a letter
- Use a conventional method of making your variables easy to read at
a quick glance. For this class, we will begin variable identifiers with
lowercase letters (eg. grade). However, if you wish to use more than
one word within the identifier, you must capitalize the following words
or parts of words (eg. semesterGrade,
billGatesWealth). Please do
not separate successive words with underscore characters
( _ ) as you may have seen in the textbook or other programming courses
(eg. semester_grade, bill_gates_wealth).
- You should usually initialize your variables at the same time that
you declare them. This is done with a declaration statement that is
also an initialization statement. C++ does not automatically initialize
all variables to the value 0 like some other programming languages.
If you do not initialize a variable to a certain value, the variable
will have an indeterminate value (also known as "garbage value").
Garbage values can corrupt the logic of your program and cause errors
when you least expect.
Examples:
int numPizzas = 3;
double carPayment = 685;
char letterGrade = 'A';
string firstName = "Bill";
Note that char values must be surrounded with single quotes
and string values must be surrounded with double quotes.
- As an exercise, write a program that prints out the indeterminate
value (garbage value) of an uninitialized variable.
Objective #3: Use constants when appropriate.
- Sometimes you need to use the same value many times throughout a program.
In this case, it is proper to use a constant rather than a variable.
- For example, if you need to use the number 12 many times because of
the fact that there are 12 items in a dozen then it would be wise and
efficient to use a constant named DOZEN
that is initialized to the value 12 rather than to type the number 12
itself throughout your program. Using the constant named DOZEN
makes your program easier for others to understand. It also makes the
program easy to upgrade down the road. For example, if the government
were to change the standard that there are 13 in a dozen rather than
12, then it would be easier to update your program if you had used the
constant DOZEN. I admit this is a far-fetched
example but it can definitely be more efficient to use constants in
such situations.
- Many programmers use the convention of having all uppercase letters
in constant identifiers. Use the underscore character ( _ ) between
consecutive words. This allows other programmers to be able to "pick
out" your constants at a quick glance.
- Here are examples of declaration statements for constants:
const double PI = 3.14159;
const double PA_SALES_TAX = 0.06;
const int SPEED_OF_LIGHT = 299792458;
Notice that you cannot use commas inside the value 299792458
Objective #4: List and explain the 5 steps of the Programming Process.
- The 5 steps of the Programming Process are:
- Define the problem and understand the given specifications.
Create a test plan during this step.
- Develop an algorithm by writing pseudocode.
- Code the program by writing it out on paper first.
- Test and debug the program.
- Document and maintain the program.
- We will discuss and use the 5 steps of the Programming Process in
our first programming assignment. You must memorize these steps however
at this time.
Objective #5: Use the arithmetic operators and assignment statements.
- The assignment
operator is the equals symbol (=)
- The assignment operator changes the value of the variable to its left
after evaluating the expression on its right!!!!!! For example,
sum
= 3 + 1000;
the variable sum ends up with the
value 1003. (Note that you cannot use a comma within numerical values
in C++ so 1003 cannot be typed as 1,003). The statement in the example above is called an assignment
statement since it assigns a value (1003) to a variable (sum). Other
examples:
salary = 40000;
poundsPressure = 15 + 12;
sum = original + 300;
salary = salary + raise;
Notice how the last example assignment statement adds salary plus raise and then assigns that sum back into the variable salary. This causes the original value stored in the variable salary to be overwritten with the new value.
-
Don't confuse declaration statements with assignment statements. The following declaration statement declares the variable num as an int data type and initializes it to the value zero. This can only be done once at the beginning of a program.
int num = 0;
An assignment statement never begins with a data type. You would only use an assignment statement if the variable was already declared earlier in the program but you need to change the value stored in the variable. So the following is an example of an assignment statement:
num = 10;
-
You can make multiple assignments in one C++
statement but I prefer separate statements for code written in this
class.
- For example:
i = j = k = 10;
// initializes all three variables to the
value, 10
is valid but three separate statements like the following example
is required by my Coding Standards:
i = 10;
j = 10;
k = 10;
- The common arithmetic operators are:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus
(like finding the remainder of a division problem)
For example, in the assignment statement
remainder = 5 % 2;
the value 1 is assigned to the variable remainder since 1
is the remainder that you get when you divide 5 by 2
- Sometimes it is convenient to store calculations in separate variables
if they are going to be used later in the program; at other times, it
is convenient to simply output the results directly to the screen
- Use "whitespace"
to make your arithmetic expressions and statements readable to fellow
programmers even if the C++ compiler doesn't require whitespace
x = 3 + y;
is better than x=3+y;
- Compound operators are sometimes useful if used carefully
- example: j += 1;
is the same as j
= j + 1;
- example: total /=
2; is
the same as total
= total / 2;
Objective #6: Be able to use the incrementing and decrementing
operators.
Objective #7: Understand and apply the order of operations.
- Remember to obey the order of operations ("Please
Excuse My Dear Aunt
Sally") that you learned in junior high or elementary
school. That is, perform the following mathematical operations in this
order: Parentheses, Exponentiation, Multiplication, Division, Addition
and Subtraction.
- However, with regard to multiplication and division, you must work
left to right within an algebraic expression. Be sure that you understand
that 8 / 4 * 2 is equal to 4. The
expression is not equal to 1 since the division is performed before
the multiplication according to the order of operations.
- With regard to addition and subtraction, you must work left to right
within an algebraic expression as well. Be sure that you understand
that 8 - 4 + 2 is equal to 6 and NOT
2.
- Note that in C++ the modulus
operator (%) has the same precedence as * and
/ but is higher in precedence than + and -. (Some other computer languages
rank multiplication and division higher in precedence than modulus.)
For example the following statement
cout << 12 / 4 % 3 - 2 * 3 << endl;
would display the value -6.
- Use parentheses if necessary to override the order of operations in
order to produce the desired result
Objective #8: Understand type coercion and type casting.
- Promotion (which is also called type coercion )
is supported in C++ to allow your expressions or statements to temporarily
convert "smaller" data types to "larger" ones in
order to provide an answer to a calculation. Promotion is performed
by the compiler in mixed mode expressions. Technically, the compiler
cannot multiply an integer with a double for example so it would automatically
promote the smaller of the two data types, the integer, to a double.
int num1 = 2;
double num2 = 2.1;
double result = 0.0;
result = num1 * num2;
As in some other programming languages, this multiplication does not
result in a "type mismatch" compile error like in C++ since
the compiler promotes num1 to a double. The variable result ends up
with the floating-point value 4.2. In this example, an integer (a 4-byte
variable) is being implicitly promoted to a larger data type double
(8-bytes).
- Type casting
(explained in Ch. 3 on pp. 104-106 in our textbook) is also allowed by the C++ compiler to allow the programmer to use the
keyword static_cast and another data
type just before the variable within a statement, but you must enclose
the variable identifier in parentheses
double circumference = 0.0;
int diameter = 2;
const double PI = 3.14;
circumference = PI * static_cast <double> (diameter);
You must type the keyword static_cast
in front of the variable that you wish to type cast. You must also
specify the new data type within angle brackets and then enclose the
variable itself within a set of parentheses. In the code segment above,
the int variable diameter
is explicitly being type casted (or sometimes just called casted)
to a double. In this example, the int variable would have been promoted
anyway by the C++ compiler even if the programmer didn't cast it to
a double. Typically casting is used to avoid integer division as explained
elsewhere in these notes.
A programmer could cast a variable "down" as well. For example,
int letter = 65;
cout << static_cast <char> (letter);
will cause the variable letter to be displayed as a capital A since
the ASCII character for the ASCII value 65 is the letter A.
There is an "older form" of type casting as explained at
the bottom of p. 24 in which just the new data type is typed in front
of the variable that you want to type cast, while the variable is still
placed in a set of parentheses.
- With a mixed mode expression such as (numPurchased
* 0.06). The result of the expression is a double even if numPurchased
is an integer data type.
Objective #9: Avoid overflow, underflow, and loss-of-precision
floating-point errors.
Objective #10: Use console I/O for input and output.
- The operator << is known as
the output operator. It is also known as the insertion operator.
- You use the output operator in statements like,
cout
<< "Hello world";
which would cause the string literal "Hello world" to appear
on the screen.
- cout is a stream which
represents data flowing from one place to another.
- The statement, cout
<< "Hello world";
, causes data to flow from your program to the screen.
- The stream, cout, leads to what your
computer considers to be its standard output device (usually
the screen).
- The operator >> is known as the input operator. It is
also known as the extraction operator.
- You use the input operator in statements like,
cin
>> numItems;
which would allow the user to input a value to be stored in the variable
numItems.
- cin is a stream of data flowing from an input device
such as the keyboard (considered to be the standard input device)
into your program.
- console I/O refers to using the keyboard and screen as the
standard input and output devices, respectively.
- For programming assignments in this CMPSC 101 course, it is necessary
to add the statement statement
system("PAUSE");
at the end of your program just before the return
0; statement. This will cause your program
to printout an extra "Press any key to continue. . ." line.
This is required due to the way the instructor grades the programs by
double-clicking the program's executable (.exe) file. If the statement
were not added to the program, the program's output may not fully display. You must include the line of code
#include <cstdlib>
at the top of the program to be able to use the system
function.
For example,
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
// the body of your program is here
system("PAUSE");
return 0;
}// end of main
Another method to solve this problem is to use the statement
getch();
just before the return 0;
statement. The getch
command stands for "get character" and it causes your program
to pause at the end of its execution to allow the user to press any
key to continue.
For example,
#include <iostream>
#include <conio.h>
int main()
{
// the body of your program is here
getch();
return 0;
}// end of main
You must include the line of code
#include <conio.h>
at the top of the program to be able to use the getch
function.
- In order to end a line in an output statement you may use the new
line character, \n, instead of endl. Examples:
cout << "Hello world"
<< '\n';
cout << "Hello world" << "\n";
cout << "Hello world\n";
which are practically equivalent to:
cout << "Hello world"
<< endl;
- Other useful "escape sequences" (since the \ is the
escape operator) are:
\t to generate
a tab
\\ to print a
backslash
\' to print a
single quote
\" to print
a double quote
- The precision manipulator allows you to limit the number of
digits that are displayed after a decimal point.
price = 2.0;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << price << endl;
will display the value 2.00.
The precision manipulator will also round a value to a given decimal
place. For example,
price = 2.348;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << price << endl;
will display the value 2.35 since the 2 in the
cout.precision(2); statement
indicates that the value is to be rounded to the second place past
the decimal point (i.e. hundredth's place). Be careful though since
the variable price in the example
above has not been permanently changed to hold the value 2.35. The
variable price still stores the value 2.348. Using the precision manipulator
only manipulates values, rounding them when applicable, for output
purposes only.
- You may use cin to allow the user to input several items with one
C++ statement. The user however must type one or more spaces between
each separate inputted value. Example:
cin
>> value1 >> value2 >> value3;
However, this prevents you from properly giving the user individual
prompt messages.
Objective #11: Use a rounding algorithm.
- The cout.precision(2); statement as described above can be used to round an outputted value to the nearest tenths place while cout.precision(0) can be used to round an outputted value to the nearest whole number. But that method of rounding does not permanently change the stored value in a given variable. It can be only used to display a value in a rounded format.
- The following algorithm, which I call the "macho rounding algorithm", is not demonstrated in your textbook. It uses a combination of type casting and type coercion to permanently change a variable's stored value to a rounded value.
- The following statements are basically equivalent in that they round any positive value stored in the variable num to the the nearest whole number
num = static_cast <int> (num + 0.5);
num = int (num + 0.5);
num = floor (num + 0.5);
- The first two examples above use type casting to truncate the decimal places of the value after 0.5 is added to it. The very first example uses the modern method of typecasting ( static_cast <int> ) while the second uses the simpler, more old-fashioned method of typecasting a double value into an integer ( int ).
- The third example uses the floor function which causes positive and negative numbers in the following set of parentheses to be truncated. You must add #include <cmath> at the top of your program in order to use the floor function.
- The following versions of the 3 example statements round num to the nearest hundredth's place.
num = (static_cast <int> ((num * 100) + 0.5)) / 100.0;
num = (int ((num * 100) + 0.5))/ 100.0;
num = (floor ((num * 100) + 0.5))/ 100.0;
- By first multiplying by 100 to move the decimal place two places to the right and then using type casting to truncate the decimal places, you are then set up to simply divide by 100.0 to move the decimal point two places back to the left.
- You must divide by 100.0 and not the whole number 100. Otherwise integer division will occur and you will lose the desired decimal digits. By using 100.0 instead of 100, you are taking advantage of type coercion (i.e. promotion) where the C++ compiler will promote the numerator int operand to a double in order to match the 100.0 denominator term which is a double.