Objective #1: Memorize the hello world program.
// type your name here
// a1.cpp
// type the day of the week that you have class
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "hello world" << endl;
system("pause");
return 0;
}// end of main
- The first line of the program is a comment statement. A comment statement begins with the // symbol. Comment statements are ignored by the computer. They are used for programmers to communicate with each other and to make notes for themselves within the program. In this course, I would like you to place the name of the program as well as the day of the week that you have class in comment statements as well.
- The lines of code #include <iostream> , #include <cstdlib> and using namespace std; must be placed at the top of each program that we write in this course. For now, just memorize them.
- main is the name of the function that makes up the most important part of this program. The main function returns an integer (i.e. a whole number.) In this case it returns the number zero as you see at the end of the program. So the keyword int is placed in front of the name of the function main.
- The curly braces { } enclose the body of the main function. The statements inside the body of the function are indented for good style and readability.
- The command cout causes the phrase hello world to be displayed on the screen. The keyword endl is a command that moves the cursor to the next line as if you typed the Enter key on the keyboard. The << symbol is the output operator and must be used to within the cout statement to make it work correctly.
- The statement system("PAUSE"); is necessary in program assignments that you turn in this semester. 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 and you will lose significant points in assignments that do not include this extra statement.
- return 0; ends the main function and causes a zero to be "returned" to the operating system indicating that the program executed successfully with no errors.
- It's good style to type the comment // end of main at the end of the main function.
Objective #2: 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 4 data
types are common in C++ and will be used in this course: int, double, string, and bool.
- 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. You do not have to memorize this number but you should know that the limit is roughly 2 billion.
- 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 you previously learned about the float
data type which can also be used to store decimal numbers, you should use the double
data type to store decimal numbers in this course.
- 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 later in this course.
- The data type bool is useful to store true and false values and we will make use of this data type later in this course.
- There are other data types that are used in C++
but we will not use them too often in this course. These include char, unsigned
char, short,
unsigned int,
long, and
unsigned long
for whole numbers and float
and long double
for decimal values.
Objective #3: Be able to write declaration statements that declare
and initialize variables.
- Variables must be declared in declaration statements before they are used in C++. Get
into the habit of doing this at the top of your program.
- 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 other programming courses
(eg. semester_grade, bill_gates_wealth).
- The examples above are poor because they don't initialize the variables to starting values as explained below. You should usually initialize your variables at the same time that
you declare them. This is done with a declaration statement that also initializes the variable. 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 a garbage value.
Garbage values can corrupt the logic of your program and cause errors
when you least expect.
Examples of GOOD declaration statements:
int numStudents = 3;
// number of students in our class
double price = 6.85; //
price of item
string userName = "Bill"; // user's name
- It is very important to include an explanatory comment to the right of your declaration statement. The comment does not have to be a complete sentence but it should give some meaningful context to the purpose of the variable in the program. The instructor deducts points on programming assignments if one or more variable declaration statements do not have inline comment statements.
- Sample exercise:
Write a valid and logical variable name for a variable that is used to store the number of bananas purchased by a customer at a grocery store.
Answer:
numBananasPurchased
- Sample exercise:
Write a declaration statement that declares a double variable named bookPrice and initializes it to the value zero.
Answer:
double bookPrice = 0.0; // price of book
Objective #4: 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; // the constant PI
const double PA_SALES_TAX = 0.06; // Pennsylvania state sales tax rate
const int SPEED_OF_LIGHT = 299792458; // the speed of light
Notice that you cannot use commas inside the value 299792458
- Sample exercise:
Write a declaration statement for a constant that stores the value 0.015 in a constant named CITY_SALES_TAX.
Answer:
const double CITY_SALES_TAX = 0.015; // Philadelphia city sales tax
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 can be used to shorten the length of assignment statements as in the examples below:
Objective #6: 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 #7: Understand promotion .
- Promotion 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).
Objective #8: Understand type casting.
- Type casting
(or sometimes called "casting") is also allowed by the C++ compiler to allow the programmer to use a
keyword int , double or 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 = double (diameter);
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,
double value = 65.99;
cout << int (value);
will cause the value 65 to be displayed since the computer "chops off" the decimal places in 65.99 in order to "fit" the value into an int.
- When an int and a double are mathematically added, subtracted, divided or multipled as in (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: Be able to allow the user to display values as output to the screen.
- The screen is called the standard output device and is also known as console output.
- The cout command is used to print numbers and text to the screen. cout is an abbreviation for "console output."
- The operator << is known as
the output operator.
- The statement
cout
<< "hello world";
causes the phrase "Hello world" to be displayed
on the screen.
- However by adding endl to the end of the statement as in
cout << "hello world" << endl;
causes a new line to be placed after the phrase so that the next phrase does not display directly next to the word "world".
- Another way to add a new line to the end of an outputed phrase is to use \n. Examples:
cout << "Hello world" << "\n";
cout << "Hello world\n";
- You could use an extra endl to display your first name on one line and your last name on the line below that as in
cout << "John" << endl << "Doe" << endl;
This can also be done with
cout << "John\nDoe" << endl;
- \n is called an escape sequence. Other useful escape sequences are
\t to generate
a tab
\\ to print a
backslash
\' to print a
single quote
\" to print
a double quote
Examples:
cout << "hello\tworld";
// causes a tab (a big gap) to display between the words "hello" and "world"
cout << "w\\o";
// causes "w\o" (the abbreviation for the word without) to appear on the screen
cout << "\'3\'";
// causes a 3 with single quotes to appear on the screen as in '3'
cout << "\"3\"";
// causes a 3 with double quotes to appear on the screen as in "3"
- You can display the numeric value stored in a variable with a cout statement as in
int numApples = 5;
cout << numApples << endl;
causes the value 5 to be displayed on the screen. Since there are no double quotes around numApples and since numApples is a previously declared variable name, the computer knows to display the numberic value that is stored in the variable. If double quotes were typed around numApples as in
int numApples = 5;
cout << "numApples" << endl;
then the word "numApples" will display on the screen.
- You can also display the value stored in a variable along with an outputed phrase or message as in
int numApples = 5;
cout << "You have purchased " << numApples << " apples." << endl;
which causes the sentence
You have purchased 5 apples.
to display. Notice the spaces that were intentionally typed after the letter 'd' in purchased and before the letter 'a' in apples. If they were not included then the output would be ugly and look like this
You have purchased5apples.
Objective #11: Be able to allow the user to input values into the keyboard.
- The keyboard is called the standard input device and is also known as console input.
- The cin command is used to allow the user to input numbers and text into variables used in your program.
- The operator >> is known as the input operator.
- You use the cin command and the input operator like this:
cin >> numItems;
which would allow the user to input a value to be stored in the variable
numItems. Do NOT use endl at the end of a cin statement like this:
cin >> numItems >> endl;
THIS CAUSES AN ERROR!
- 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:
cout << "Enter three bowling scores separated by blank spaces: ";
cin
>> value1 >> value2 >> value3;
Objective #12: Use a simple rounding algorithm.
- The cout.setf and cout.precision commands can be used to limit or force an exact number of
digits that are displayed after a decimal point.
price = 2.0;
cout.setf(ios::fixed);
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.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).
- The cout.precision(2); statement as described above can be used to round an outputted value to the nearest hundredths place. The cout.precision(1); statement will round a value to the nearest tenths place and cout.precision(0) can be used to round an outputted value to the nearest whole number.
- But this 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 in a cout statement.
- For example:
double decimalNumber = 1.4;
cout.setf(ios::fixed);
cout.precision(0);
cout << decimalNumber << endl;
// the number 1 is displayed
decimalNumber = decimalNumber + 0.6;
cout << decimalNumber << endl;
// the number 2 is displayed since the value stored in decimalNumber was not permanently changed to the value 1 by the cout.precision(0); statement
Objective #13: Use the "macho" rounding algorithm.
- I call the following algorithm, the "macho rounding algorithm." It uses a combination of type casting and promotion 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 = int (num + 0.5);
num = floor (num + 0.5);
- The first example above uses type casting to truncate the decimal places of the value after 0.5 is added to it.
- The second 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 = (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.
Objective #14: 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.