LM - Chapter 02 PDF
LM - Chapter 02 PDF
LM - Chapter 02 PDF
PROCEDURE 1. Students should read the Pre-lab Reading Assignment before coming to lab.
2. Students should complete the Pre-lab Writing Assignment before coming to lab.
3. In the lab, students should complete Labs 2.1 through 2.4 in sequence. Your
instructor will give further instructions as to grading and completion of the lab.
Approximate Check
completion Page when
Contents Prerequisites time number done
Pre-lab Reading Assignment 20 min. 14
Pre-lab Writing Assignment Pre-lab reading 10 min. 19
Lesson 2A
Lab 2.1
Working with the cout Pre-lab reading 20 min. 20
Statement
Lab 2.2
Working with Constants, Understanding of 30 min. 21
Variables, and Arithmetic variables and
Operators operators
continues
13
14 LESSON SET 2 Introduction to the C++ Programming Language
Lesson 2B
Lab 2.3
Rectangle Area and Perimeter Understanding of 30 min. 22
basic components
of a program
Lab 2.4
Working with Characters Completion of 30 min. 22
and Strings labs 2.12.3
PRE - L AB RE A D I N G AS S I GNMEN T
#include <iostream>
using namespace std;
int main()
{
float radius;
radius = 4.0;
return 0;
}
Everything in bold (everything above the int main() statement) is considered the
header or global section. Everything else is the main section.
Pre-lab Reading Assignment 15
Recall from Lesson Set 1, that every program needs other modules attached so that
it may execute properly. Your instructor will generally tell you which libraries are
needed for each particular programming assignment; however, in time you will
learn this task for yourself.
Every C++ program has a main function which indicates the start of the
executable instructions. Every main must begin with a left brace { and end with
a right brace }. The statements inside those braces will be explained as we
progress through this lesson.
Memor y
Memory storage is the collection of locations where instructions and data that are
used by the program are temporarily stored. Recall from Lesson Set 1 that a com-
puter only understands a sequence of 1s and 0s. These are binary digits or bits
(BInary digiTs). Eight of these brought together are called a byte, which is the
most common unit of storage. These chunks of memory can be thought of as hotel
mailboxes at the registration desk. The size of each of those boxes indicates the
type of mail that can be stored there. A very small mailbox can only hold notes
or postcards. Larger mailboxes can hold letters, while even larger ones can hold
packages. Each mailbox is identified by a number or name of an occupant. We
have identified two very important attributes of these mailboxes: the name or num-
ber, which indicates the mailbox that is being referenced, and the size, which indi-
cates what type of data can be placed there.
Example: postcards Jim is an indication that the mailbox called Jim can only hold
postcards, while the statement packages Mary indicates that the mailbox called
Mary can hold large packages. Memory locations in a computer are identified by
the same two attributes: data type and name.
Much of programming is getting data to and from memory locations and thus it
is imperative that the programmer tell the computer the name and data type of
each memory location that he or she intends to use. In the sample program the
statement float radius does just that. float is a data type that indicates what
kind of data can be stored and radius is the name for that particular memory
location.
16 LESSON SET 2 Introduction to the C++ Programming Language
Identifiers in C++
Identifiers are used to name variables, constants and many other components of
a program. They consist exclusively of letters, digits and the underscore _ char-
acter. They cannot begin with a digit and cannot duplicate reserved words used
in C++ such as int or if. All characters in C++ are case sensitive; thus memory
locations called simple, Simple, and SIMPLE are three distinct locations. It has
become standard practice among programmers to make constants all uppercase
and variables predominantly lowercase characters.
The statement const double PI = 3.14; in our sample program is
contained in the global section. It defines a memory location called PI to be a
constant holding a double (a data type discussed shortly) value equal to 3.14
which will not change during the execution of the program.
The statement float radius; in the sample program is contained in the
main section. It defines a variable memory location called radius that holds a
float- ing point data type (type discussed shortly) which can be changed during the
exe- cution of the program.
Both of these statements are called definitions. They reserve by name
enough memory to hold the data type specified.
Variables, like constants, can be given an initial value when they are defined,
but that value is not permanent and can be altered. For example:
int count = 7; // Defines a variable memory location called count that
// initially has the value of 7
count = count + 1; // count is now altered
Data Types
As noted earlier, computer memory is composed of locations identified by a data
type and a name (like the room number of a hotel mailbox). The data type indi-
cates what kind of data can be stored, thus setting the size of that location.
String Type: A variable defined to be character data can store only one charac-
ter in its memory location, which is not very useful for storing names. The string
class has become part of standard C++ and, although not a primitive type defined
by the language, it can be used as a type for storing several characters in a mem-
ory location. We must include the string library (#include <string>) in the pro-
gram header. The following statement defines a string initialized to Daniel:
string name = "Daniel"; Note that a string is enclosed in double (not single)
quotes. Thus the string "a" is not the same as the character 'a'.
Assignment Operator
The = symbol in C++ is called the assignment operator and is read is assigned
the value of. It assigns the variable on its left the value on its right. Although
this symbol looks like an equal sign, do not confuse it with equality. The left hand
side must always be a variable. For example, count = 8; is a legitimate statement
in C++, however 8 = count; generates a syntax error.
Fundamental Instructions
Most programming languages, including C++, consist of five fundamental instruc-
tions from which all code can be generated.
18 LESSON SET 2 Introduction to the C++ Programming Language
Example:
int count;
int total;
This last statement may seem a bit confusing. Starting with the right side, it
says to get the value that is in total (10 in this case), add it to the value
that is in count (7 in this case), and then store that combined sum (17) in
the memory location called total. Notice that total, which was initially
10, gets changed to 17.
2. Output Statements: These instructions send information from the computer
to the outside world. This information may be sent to the screen or to some
file. In C++ the cout << statement sends information to the screen. The
#include <iostream> directive must be in the header for cout to be used.
The above statement sends whatever value is stored in the variable total
to the screen. C++ uses the semicolon as a statement terminator.
We can output literal strings (such as Hello) by inclosing them in
double quotes.
The << operator acts as a separator for multiple outputs.
cout << "The value of total is " << total << endl;
The endl statement causes the cursor to be moved to the beginning of the
next line.
The remaining three fundamental instructions will be explained in
future labs.
Pre-lab Writing Assignment 19
Arithmetic Operators
Programming has the traditional arithmetic operators:
Operation C++ Symbol
addition +
subtraction -
multiplication *
division /
modulus %
Integer division occurs when both the numerator and denominator of a divide
operation are integers (or numbers stored in variables defined to be integers). The
result is always an integer because the decimal part is truncated or chopped from
the number. Thus 9/2 will give the answer 4 not 4.5! For this reason there are two
division operations for integer numbers. The modulus operator, (%) used only with
integers, gives the remainder of a division operation. 9/2 gives 4 while 9 % 2 gives
1 (the remainder of the division).
Example:
int count = 9;
int div = 2;
int remainder;
int quotient;
You should go back and review the sample program on the first page of the Pre-
lab Reading Assignment. By now you should understand most of the statements.
PRE - L AB W RI TI N G AS S I GNMEN T
Fill-in-the-Blank Questions
1. A is a memory location whose value cannot change
during the execution of the program.
2. is a data type that only holds numbers with no fractional
component.
3. is a data type that holds numbers with fractional
components.
4. is an arithmetic operator that gives the remainder of a
division problem.
20 LESSON SET 2 Introduction to the C++ Programming Language
L ES S ON 2 A
#include <iostream>
using namespace std;
int main()
{
return 0;
}
Lesson 2A 21
Exercise 2: Change the program so that three blank lines separate the tele-
phone number from the address. Compile and run the program.
Exercise 3: Change the program so that the following (but with your name and
address) is printed. Try to get the spacing just like the example. Compile
and run the program.
************
Programmer: Deano Beano
123 Markadella Lane
Fruitland, Md. 55503
Telephone: 489-555-5555
************
#include <iostream>
using namespace std;
int main()
{
area // definition of area of circle
// Fill in the code for the cout statement that will output (with description)
// the circumference
// Fill in the code for the cout statement that will output (with description)
// the area of the circle
return 0;
}
22 LESSON SET 2 Introduction to the C++ Programming Language
Exercise 2: Fill in the blanks and the cout statements so that the output will
produce the following:
The circumference of the circle is 33.912
The area of the circle is 91.5624
Exercise 3: Change the data type of circumference from float to int. Run the
program and record the results.
The circumference of the circle is .
The area of the circle is .
Explain what happened to get the above results.
L ES S ON 2 B
#include <iostream>
#include <string>
using namespace std;
// Definition of constants
const string FAVORITESODA = "Dr. Dolittle"; // use double quotes for strings
const char BESTRATING = 'A'; // use single quotes for characters
int main()
{
Lesson 2B 23
return 0;
Exercise 2: Fill in the indicated code, then compile and run the program.
Continue to work on the program until you have no syntax, run-time, or
logic errors.
The output should look similar to the following:
The preferred soda is Dr. Dolittle
The preferred snack is crackers
Out of 250 people 148 chose these items!
Each of these products were given a rating of A from our expert tasters
The other products were rated no higher than a B
Exercise 3: Is it possible to change the choice of FAVORITESODA by adding
code within the main module of the program? Why or why not?
Exercise 4: Is it possible to change the choice of favoriteSnack by adding code
within the program? Why or why not?