Click here to CREATE ANSWER SHEET for LAB 3

Lab 3 -- C++ Program Construction, Simple Data Types, and Strings

Objectives:

Sections:
  1. Introduction
  2. Basic Structure of a C++ program
  3. Constants and Variables
  4. C++ Naming Convention
  5. Numeric Data Types
  6. Numeric Operators
  7. Assignment Statement
  8. C++ Output Statement
  9. Character and String Data Types
  10. Code for Lab 3

Introduction
Our first step in learning how to program is to learn some C++ basics so that we can implement a program design using the C++ language. To implement an algorithm as a program, we must first learn how to perform certain tasks in the language we are using.

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
Every C++ program has a very similar structure. A simple C++ program consists of four components:

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.


Exercise 1:
LOG ON and GET A TERMINAL WINDOW:  Use your course account information to access ranger. For Login username enter your course account's C-number (that is, the 8 character login username you were assigned; for example, c1155913). For Password, enter your course account's password; for example 74ab2w45. Your password will not be displayed so be careful in your typing.

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:

cp   $CLA/cla3a.txt  cla3a.txt

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.

Exercise 2:
Consider the C++ program below (scroll down to see it). There are several blanks to be filled in. Compare it to the examples that you have seen today and determine what should be in the blanks on the indicated lines. Place your answers on the answer sheet. What should be in the blank on
a.   line 5.
b.   line 9.
c.   line 12.
d.   line 15.
e.   line 24.



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
Each of the programs that we have seen today require the storage of data. In order to work with data, it must be in memory. In C++, data can be stored in either a variable or a constant. A variable is a place (or location) in memory capable of storing a data value; the data value in this type of memory location may vary. A constant is a memory location in which the data stays constant. For either type of memory location, a name, referred to as an identifier, may be attached to that location. When we wish to reference a memory location during program execution, we use the identifier name for that memory location. In C++, an identifier is a word that begins with a letter followed by any combination of letters and digits. (In C++, the underscore character _ is considered a letter.) Although the C++ standard imposes no limit on the number of characters in a name, sometimes specific implementations of C++ do impose limits; however by far the majority of implementations allow identifiers of at least 31 characters.

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.




Exercise 3:
Indicate on the answer sheet whether each of the following is a valid or invalid name for an identifier. If invalid, explain why the name can't be used.

a.   average
b.   thisIsALongName
c.   howLongIsTooLong?
d.   3rd
e.   float
f.   lengthInSqFt


C++ Naming Conventions.
In C++ we select identifiers that are descriptive of the data being stored or the task being solved. We will use the following rules for naming identifiers:
  • For variable names, we begin with a lowercase letter and capitalize each successive word. Examples include payRate, lastName, and numberOfHoursWorked.
  • For constants, we capitalize every letter and use underscores to separate the English words. Examples include PI, MAX_WORDS, and OVERTIME_RATE.
  • Programmer written functions will be capitalized in the same way as variable names but they will begin with a capital letter. Examples include FindArea and PrintResults.


Exercise 4:
For each of the identifiers below, select a meaningful identifier name that adheres to the naming conventions described above.
a.   A variable that could contain a test score.
b.   A constant that could contain the number of minutes in an hour.
c.   A function that could be used to convert a temperature in Fahrenheit to a temperature in Celsius.


Numeric Data Types
Once we know what values we wish to store and have chosen names for them, we must decide what type of data will be placed in memory. We must also decide whether the value will change or stay constant. We may also wish to perform calculations on the values. Therefore, we must be aware of the operations that can be performed on various 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;




Exercise 5:
On the answer sheet show C++ statements to declare the variable QUARTER to be a constant which contains the value 25 and the variable age and weight to be integer variables and the variable length to be a float variable.

Simple Numeric Operators
Some of the operators that may be used on numeric data include:

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:

    • All parenthesized expressions are evaluated first.
    • The operator * is performed next.
    • The operators + and - are performed last.

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


Exercise 6:
Evaluate these expressions and place your answer on the answer sheet:
a.   2 + 3 * 4 - 5
b.   14 + 8 * 2
c.   17 * (( 3 - 1 ) * 7 )
d.   2.0 + 3.0 * (2.0 - 6.0 * 4.0)


Assignment Statements.
Now that we know how to set up memory locations, what type of data can be placed in memory locations, and what types of arithmetic operations can be performed on each type of data, we need to know how to place data into a the memory location of a variable. We will accomplish this by using an assignment statement or by using the C++ input statement.

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++,

2A + B

The resulting C++ expression is:

2*A + B



Exercise 7:
On the answer sheet write valid C++ assignment statements for the following mathematical expressions:

a.   A = .5 b h
b.   E = J(J + 1)h
c.   Place the sum of the values in t1, t2, and t3
into the variable sum.


C++ Output Statements
To place the results of computations or the current contents of a memory location on the standard output device (usually the screen), we use a special variable called cout along with the insertion operator ( << ). For example:

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:

cout << "Welcome" << endl;

cout << "to 2170" << endl;

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 << "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:
Suppose a program contains the following variable declarations and assignments:

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:
Copy the C++ program cla3b.cpp from the directory $CLA to your directory. Use the command

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:
Compile and run this program after you have looked at it and made sure that you understand it. To compile the program, type:

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
In addition to numeric data, character data may also be placed in memory. To declare a variable which can contain a single character value, use the C++ reserved word char. Suppose we wished to declare the variables initial1 and initial2 to contain any single character value. We would use:

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:
Using the example above, write C++ statements to:

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..


Exercise 13:

Submit the log file you created in Exercise 11 by typing

          $ handin lab3log lab3ex11.log
Exercise 14:

One 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.



Once you are done, you will need to log off ranger. Enter   $ exit   to exit the (sakura) terminal window. Depending on how you logged in to ranger you will need to enter $ exit one or more times to get completely logged off the system.

 

 

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;
}