Lab 3 -- C++ Program Construction, Simple Data Types, and Strings
Objectives:
Introduction
ON DOING CLOSED LABS: It is worth repeating: Read everything! Careful reading of the closed lab instructions is a must. You simply cannot delve into a lab and start typing. Read the material and, only where and when directed, enter commands. Be patient, both with yourself and with the lab material---remember, you are new to this stuff and it will take a while to become proficient.
ANSWER SHEET: If you have not already done so, click on the link at the top to create an answer sheet window.
Basic Structure of a C++ program
We will discuss each of these components briefly. Consider the following C++ program.
The four components are labeled in the comments (text preceded on the same line by two slashes: //). Line
numbers have been added for discussion purposes only. They are not part of the program.
1 // 2 //This is a simple C++ program to determine the area and 3 //circumference of a circle of radius 12. 4 // 5 6 //preprocessor directives 7 #include <iostream> 8 9 //using directive 10 using namespace std; 11 12 //constants and declarations section 13 const float PI=3.14159; //define the constant pi 14 float FindArea(float radius); //declare FindArea 15 float FindCircumference(float radius); //declare FindCircumference 16 17 //required main function 18 int main() 19 { 20 float radius = 12; //the radius of the circle 21 float area; //the area of the circle 22 float circumference; //the circumference of the circle 23 24 //determine the area and circumference 25 area = FindArea(radius); 26 circumference = FindCircumference(radius); 27 28 //output the results 29 cout << "A circle of radius 12 has an area of: " << area << endl; 30 cout << "It also has a circumference of: " << circumference << endl; 31 32 return 0; 33 } 34 35 //additional C++ functions 36 37 //This function determines the area of a circle 38 float FindArea(float radius) 39 { 40 return PI * radius * radius; 41 } 42 43 //This function determines the circumference of a circle 44 float FindCircumference(float radius) 45 { 46 return 2.0 * PI * radius; 47 }
Lines 1 through 6 are either comments or are blank. Comments are lines used to explain the various parts of a program. These comments are ignored by the compiler and are not executable. A comment begins with a double slash (//). Everything from the // to the end of the line is ignored by the compiler.
Line 7 is a preprocessor directive. Preprocessor directives begin with the pound sign (#). The #include directive directs the compiler to include the contents of a file with your program prior to compiling. The angle brackets (<, >) indicate that the file is in the standard C++ include library.
Line 10 is a "using" directive that allows the use of all identifiers defined in the special memory location namespace std. (examples: cout, and endl)
Lines 13 - 15 contain the constant and function declaration section. In this particular program, line 13 declares and defines a constant (the word const means constant). Lines 14 and 15 declare two functions that will be used in the main function and defined after the main function is defined. We will discuss these two lines thoroughly in a later lab.
Line 18 starts the main function. Every C++ program must have a main function. This is where the execution of the program starts when the program is compiled and when we read C++ programs, this is where we should start reading. Think of it as if it were the first chapter in a book we are reading. Line 18 is called a function heading. Think of it as the title of the function. Line 19 has an opening curly brace, { , and line 33 has a closing curly brace, }. The opening curly brace signifies that this is the start of the body of the function and the closing curly brace signifies that this is the end of the function.
Lines 20-22 in the main function are called declaration statements. C++ programs use three types of "words." Reserved words are words that are predefined words in the language and their meaning can not be changed. An example of such a word is int which means integer data type. We will be learning a lot of reserved words during the semester. A second set of predefined words available for use by a programmer, library identifiers, can have their meaning changed by a programmer. An example of a library identifier is cout which means to output information. The third type of "word" is programmer-defined identifiers. For example in this problem, radius, area, and circumference are such words. We must warn the compiler that we are going to use these words by defining them. The programmer should use words that have meaning to the problem. Notice that a semicolon ends each line of this section.
Lines 24 through 32 form the statement section and statements are placed here to solve the problem. As in the previous section of the main function, each statement in this section must end with a semicolon.
Lines 37-41 and 43-47 contain two additional functions. The first function FindArea determines the area of a circle and the second function FindCircumference determines the circumference of a circle.
Once you have an active UNIX login,
you will want to open up a "better" Terminal window.
It is "better" in the sense it is clearer to read and easier to change
the font size. (Recall, this "better" terminal window comes
from running an application called sakura.) Enter the
following command
$
terminal &
Change directories to CLA (i.e. type cd ~/CLA). Copy the file cla3a.txt to your directory by typing:
Line numbers have been added to this program so that you can identify the various components easily.
On the answer sheet, identify (by giving line numbers) the following parts of the C++ program:
a. The preprocessor section.
b. The constant and function declaration section.
c. The main function heading.
d. The body of the main function.
e. The declaration statements in the main function.
f. The statement section of the main function.
g. The additional functions section.
1 //This program determines the cost for renting an apartment for 2 //a set number of years. 3 4 //preprocessor section 5 # ____________6 using namespace std; 7 8 //constants and function declarations 9 __________ int RENT_RATE = 350; 10 void printRentInfo (int years, int costOfRent); 11 12 __________ main () 13 { 14 int years = 3; //# of years over which rent is computed 15 int costOfRent____ //cost for renting 16 17 //calculate the rent 18 costOfRent = years * RENT_RATE; 19 20 //output the results 21 printRentInfo(years, costOfRent); 22 23 return 0; 24 ______ 25 26 //This function prints the rent information. 27 void printRentInfo (int years, int costOfRent) 28 { 29 cout << "The cost per month for rent is: " << RENT_RATE << endl; 30 cout << "The number of years is: " << years << endl; 31 cout << "The total cost of rent is: " << costOfRent << endl; 32 }
Constants and Variables
For example, sum, x, product, r2d2, a1, fairlyLongName, and hoursWorked are all valid names. Invalid names include 4thofjuly, x-axis, and c++ . C++ does distinguish between upper and lower case letters; we say that C++ is case-sensitive. SUM, Sum, and sum all refer to different identifiers. It is generally a bad idea to use names that differ only in case.
One should choose names that have a meaning close to what they represent. (We call identifier names that are indicative of their use mnemonic. In this context, mnemonic means "assisting remembering".) For example, use rateOfPay to represent a person's rate of pay per hour instead of x.
As mentioned in a previous section, C++ has special words, called reserved words, which have a specific meaning unique to C++. These words cannot be used for other purposes. Therefore these reserved words can not be used as symbolic names. Look in your book for a complete list of all reserved words. A few of these words are float, int, main, and char.
Numeric Data Types
Our first data type is the integer data type. When we tell C++ that a variable is an integer type, we are restricting the type of data that can be stored in the variable to an integer. Therefore, only whole numbers (-50, 2, 1000, and 0 are examples) can be stored in this memory location. The size of the integer is limited by the computer's architecture.
To declare the variables count and numItems to be integer variables, we use the C++ variable declaration statement:
int count, numItems;
or perhaps
int count; // Number of customers
int numItems; // Number of items purchased
Note the semicolon at the end of each of the C++ statements above. The semicolon is required.
To declare the integer constant HOURS_PER_DAY to contain the value 24, we use the C++ statement:
const int HOURS_PER_DAY = 24;
Notice that this declaration is very similar to the declaration of a variable. In the above example, however, the C++ reserved word const makes the name refer to a value (24) that cannot be changed after it is initially defined.
A second type of data that can be stored in a memory location is the float type which may contain real numbers, or numbers that have a decimal point like 3.5, -.0048, or 12.5896. A real (floating point) number may use an e to indicate the number should be multiplied by powers of ten. The number 2.75 can be represented by any of the following:
2.75e0, .275e1, 27.5e-1, etc.
To declare the constant PI to contain 3.14159 and the variables radius and area to contain real values, the C++ reserved word float is used.
const float PI = 3.14159; float radius, area;
Simple Numeric Operators
Operator |
Integer Example |
Real Example |
+ Add |
2 + 3 is 5 |
3.56 + 4.01 is 7.57 |
- Subtract |
4 - 1 is 3 |
8.45 -10.3 is -1.85 |
* Multiply |
4 * 3 is 12 |
0.2 * 100.0 is 20.0 |
There are no surprises in this table. In later labs we will consider additional operators.
If there are more than one operator in an expression, we use the following rules to decide which operator will be performed first:
If there are more than one of the operators * in an expression, then the leftmost operator is performed first. Similarly if there are more than one of the operators + and - in an expression, then they are performed from left to right.
For example: 3 * 2 * (13 - 3) + 2 = 3 * 2 * 10 + 2 (parenthesis first) = 6 * 10 + 2 * next (left-most) = 60 + 2 * next = 62 + last
Assignment Statements.
A value may be placed into a memory location with the assignment statement which has the form:
variable_name = expression;
where the expression is always evaluated first, then the resulting value is assigned to the variable. Note that this value replaces any "old" value that the variable had. For example, the assignment:
int age;
age = 21;
gives the variable age the value 21. If the next statement is:
age = age * 2;
then 21 is replaced with 42.
Note: The data types of the variable on the left and the expression on the right should agree. It would not be proper to use:
age = 21.5;
Mathematical expressions and equations can be converted to C++ by using the operators and operator priorities discussed above. Care must be taken to make sure that the operations with highest priority are done first. For example, to convert the following mathematical expression to C++,
The resulting C++ expression is:
2*A + B
Exercise 7:
C++ Output Statements
cout << "Welcome to 2170" << endl;
This statement displays the string of characters Welcome to 2170 on the "standard output device", usually the monitor screen. A string is a sequence of characters enclosed in double quotes; the characters inside the quotes will be printed but the quotes will not be printed. The identifier endl (meaning "end line") is a special C++ feature called a manipulator. We will discuss manipulators in a later lab. For now, just remember that endl lets you finish an output line. As a second example:
would cause the characters Welcome to appear on one line and the characters to 2170 to appear on the following line. We can output a string of characters and we can also output the value contained in a variable. For example:cout << "Welcome" << endl;
cout << "to 2170" << endl;
cout << "Your age is " << age << endl;
displays two items; the character string "Your age is" and the value of age. If age contained the value 21, then the output would appear as:
Your age is 21
Exercise 8:
int test1Score = 90; int test2Score = 80; int sumOfScores = test1Score + test2Score;Write output statements that would produce the output below (notice that the values stored in the variables have been output):
Test Score 1 = 90 Test Score 2 = 80 The sum of the scores = 170
Place your statement(s) on the answer sheet.
Exercise 9:
cp $CLA/cla3b.cpp cla3b.cpp
The program solves the problem of entering data concerning a landlord who owns an apartment and wishes to know what his earnings are on the apartment to date. The values known are the rent per month and the number of months rented. The variables for these two values are
rent and numMonths. The landlord has hired an overseer to take care of the apartment who receives a commission of 5% of the earnings from the apartment. Since this is a constant rate, the constant RATE has been chosen to hold this data. Assignment statements have been used to place values in the variables rent and numMonths.Read this program to make sure you understand it. There is nothing to turn in as a result of this exercise.
Exercise 10:
c++ cla3b.cpp -o cla3b
To run the program, type:
cla3b
Make sure you understand the output generated by the program. There is nothing to turn in as a result of this exercise.
Character and String Data Types
char initial1, initial2;
Values can be placed into the variables using assignment statements or cin.
initial1 = 'J';
initial2 = 'K';
places the characters J and
K into the two variables respectively.
Exercise 11:
In the problem from Exercise 9, suppose that the landlord wishes to
have the initials of the person renting his apartment printed as well as the earnings
of the apartment. Copy the C++ program cla3c.cpp
to your
directory. This program contains the initials of the person renting the apartment,
the rent per month, and the number of months the apartment has been rented.
It then prints out the earnings. Compile and run the program to make sure you
know what it is printing. Then use an editor to modify the program so that it prints
your initials. For example -- to start vi type:
vi cla3c.cpp
Create a script log, called lab3ex11.log of a cat, a compile, and a run of these activities by typing
script lab3ex11.log cat -n cla3c.cpp c++ cla3c.cpp -o cla3c cla3c exit
A value of type char is limited to a single character. A string is a sequence of characters, such as a word, a name, or an address enclosed in double quotes. For example, the following are strings in C++:
"J. D. Johnson", "4509 Harrison Street", and "$39,000.00"
The quotes are not considered part of the string but are there to distinguish the string from other parts of the program. A string containing no characters "" is called the null string or the empty string.
The following statement declares a variable to be of type string and assigns the string Johnson to this variable:
string lastName="Johnson";
The data types mentioned previously in this lab are built-in data types. The string data type is programmer-defined and is supplied by the C++ standard library. Thus we must include in any program that uses strings the following preprocessor directive.
#include <string>
This directive contains declarations about the string data type.
Operations on string data include comparing the values of strings, searching a string for a particular character, and joining one string to another. In this lab we wish to discuss the operation that allows us to join one string to another called concatenation. This operation is performed by using the + operator. The result of concatenating (joining) two strings is a new string containing the characters from both strings. For example, given the statements:
string lastName = "Smith"; string firstName = "Jill"; string name; name = firstName + lastName; cout << name << endl;
This statement retrieves the value of firstName from memory and concatenates the value of lastName to form a new, temporary string containing the characters
"JillSmith"
Notice that no space is added between the first and last name. To add that space, we could use the assignment statement below to replace the one above.
name = firstName + " " + lastName;
Exercise 12:
a) Declare a variable lastNameFirst.
b) Use concatenation to place into the variable
lastNameFirst the string Smith, Jill
Place your answers on the answer sheet.
Submit the log file you created in Exercise 11 by typing
$ handin lab3log lab3ex11.logOne last thing to do! From the PC you are working on, you must also submit the answer sheet (AnswerSheet3.pdf) using the following directions:
Congratulations!
You have finished Lab 3.
Code for Lab 3 (Do not copy/paste)
1 // File Name: cla3a.txt 2 // Purpose: This program calculates a landlord's earnings 3 // on an apartment given the rent per month, the 4 // number of months rented and a deduction of 5% 5 // commission for an overseer. 6 7 #include <iostream> 8 using namespace std; 9 10 const float RATE = 0.05; // overseer's commission rate 11 float CalcEarnings (float rent, int numMonths); 12 void printResults (string last, char middle, string first, 13 float rent, int numMonths, float earnings); 14 15 int main() 16 { 17 //variable declarations... 18 float rent; // rent per month 19 int numMonths; // number of months rented 20 float earnings; // earnings on the apartment 21 string lastName; // the last name of the tenant 22 char middleInitial; // the middle initial of the tenant 23 string firstName; // the first name of the tenant 24 25 //set values for apartment renter, rent/month and number of months 26 //the apartment has been rented. 27 lastName = "Smith"; 28 middleInitial = 'A'; 29 firstName = "Jill"; 30 rent = 350.00; 31 numMonths = 12; 32 33 //calculate earnings 34 earnings = CalcEarnings (rent, numMonths); 35 36 // display results 37 PrintResults (lastName, middleInitial, firstName, rent, numMonths, earnings); 38 39 //exit 40 return 0; 41 } 42 43 //This function calculates the earnings for an 44 //apartment. 45 float CalcEarnings (float rent, float numMonths) 46 { 47 return (1.0 - RATE) * rent * numMonths; 48 } 49 50 //This function displays all of the apartment information 51 void PrintResults (string last, char middle, string first, 52 float rent, int numMonths, float earnings); 53 { 54 cout << "The name of the apartment renter is: " 55 << first << " " << middle << " " << last << endl; 56 cout << "The rent per month is: " << rent << endl; 57 cout << "The apartment has been rented for "; 58 cout << numMonths << " months." << endl; 59 cout << "The overseer receives a " << 100 * RATE; 60 cout << "% commission rate. " << endl; 61 cout << "The earnings were: " << earnings << endl; 61 } // File: cla3b.cpp // Author: // Purpose: This program calculates a landlord's earnings // on an apartment given the rent per month, the // number of months rented and a deduction of 5% // commission for an overseer. #include <iostream> using namespace std; int main() { //variable and constant declarations... const float RATE = 0.05; // overseer's commission rate float rent; // rent per month float numMonths; // number of months rented float earnings; // earnings on the apartment //assign values and calculate earnings rent = 250; numMonths = 7; //calculate earnings earnings = (1.0 - RATE) * rent * numMonths; // display results cout << "The rent per month is: " << rent << endl; cout << "The apartment has been rented for "; cout << numMonths << " months." << endl; cout << "The overseer receives a " << 100 * RATE; cout << "% commission rate. " << endl; cout << "The earnings were: " << earnings << endl; //exit return 0; } // File: cla3c.cpp // Author: // Purpose: This program calculates a landlord's earnings // on an apartment given the rent per month, the // number of months rented and a deduction of 5% // commission for an overseer. Initials for the // apartment renter are also output. #include <iostream> using namespace std; int main() { //variable and constant declarations... const float RATE = 0.05; // overseer's commission rate float rent; // rent per month float numMonths; // number of months rented float earnings; // earnings on the apartment char firstInitial, middleInitial, lastInitial; // initials of the apartment renter //assign values and calculate earnings rent = 250; numMonths = 7; firstInitial = 'J'; middleInitial = 'A'; lastInitial = 'C'; //calculate earnings earnings = (1.0 - RATE) * rent * numMonths; // display results cout << "The initials of the apartment renter are: " << firstInitial << middleInitial << lastInitial << endl; cout << "The rent per month is: " << rent << endl; cout << "The apartment has been rented for "; cout << numMonths << " months." << endl; cout << "The overseer receives a " << 100 * RATE; cout << "% commission rate. " << endl; cout << "The earnings were: " << earnings << endl; //exit return 0; }