+ All Categories
Home > Documents > C++ Lab Manual

C++ Lab Manual

Date post: 19-Oct-2015
Category:
Upload: scribddownloaded
View: 110 times
Download: 4 times
Share this document with a friend
Description:
C++ Lab Manual

of 88

Transcript
  • Lab Manual for

    Problem Solving, Abstraction, and Design Using C++, third

    edition

    Lynn Lambert, updated by Richard RossChristopher Newport University

    Newport News, Va

    June 8, 2000

    Laboratory 1 Introduction to C++

    1.1 Objective

    In this lab, you will learn

    the form of a C++ program what the components of a C++ program are how to write comments about compiler directives how to trace programs

    1.2 Correspondence to Text

    The material in this lab best corresponds to sections 2.1-2.6 in the text.

    1.3 Introduction

    This lab course provides an introduction to computer programming using the C++ language. Theversion of C++ that will be used is called ANSI Standard C++, or just Standard C++. (ANSIis the name of the institute that developed the standard). In this lab, you will see your first C++program. You will also trace through a C++ program.

    1

  • 1.4 Examining a C++ program

    Lets look at a C++ program.

    Copy intocm.cpp into your directory. Your instructor will tell you how to do that. Edit the file intocm.cpp. Your instructor will tell you the best way to edit your file.

    Note on Lab Manual format: I will use a bullet like this whenever there is somethingthat you need to do on the computer.

    The file should look something like this:

    // InchToCm// This program inputs a real number inches and// outputs its centimeter equivalent (also a real// number)

    #include using namespace std;

    int main(){float centimeters, inches;

    cout inches;centimeters = inches * 2.54;cout

  • // your name// InchToCm

    Comments tell people reading the program something about the program. The compilerignores these lines.

    1.4.2 Compiler Directives

    After the initial comments, you should see the following line:#include This is called a compiler directive. It tells the compiler to do something. Compiler directivesalways start with a # sign. In this case, the compiler directive includes the information in the fileiostream as part of your program. You will almost always have at least one include file in yourprogram. These header files are stored in a library that we will learn more about in subsequentlabs. (Note: Older C++ programs use a .h as part of the include file name, while Standard C++include files have no extension, or .h).

    The next line, using namespace std;, tells the compiler that the objects that well beusing are in the standard namespace. This line should be in all of your programs. Note that thisline ends in a semicolon.

    1.4.3 The function main

    The next nonblank line int main () gives the name of a function. There must be exactly onefunction named main in each C++ program, and main is the function where program executionstarts when the program begins running. The int indicates the function returns an integer. Youwill learn more about functions in the next two weeks, but essentially functions are units of C++code that do a particular task. Large programs will have many functions just as large organizationshave many functions. Small programs, like smaller organizations, have fewer functions. Theparentheses following the words int main is a list of arguments to the function. In the case ofthis function, there are no arguments. Arguments to functions tell the function what objects touse in performing its task.

    The curly braces on the next line and on the last line of the program determine thebeginning and ending of the function.

    1.4.4 Variable Declarations

    The line after the opening curly brace, float centimeters, inches; is called a variable dec-laration. This line tells the compiler to reserve two places in memory that are the size of a realnumber (thats what the float indicates). The memory locations will have the names inches andcentimeters associated with them. You will often have many different variables of many differenttypes.

    3

  • 1.4.5 Executable Statements

    Output and InputThe statements following the variable declaration up to the close curly brace are executablestatements. The executable statements are statements that will be executed when the programis run. cout and the output stream operator (

  • arguments are all part of C++ syntax. When you compile a program, if it has syntax errors, youwill get a listing of those errors and you must fix the syntax errors before the compiler can createan executable file which can be loaded and run.

    The general form of a C++ program is given below:

    // program name// other comments like what program does and your name

    # include using namespace std;

    int main (){

    variable declarations;

    executable statements:} // end main

    1.4.7 Testing your Understanding

    Throughout this lab manual, there are places where you have the opportunity to check yourunderstanding. This is just such a place. Ask your instructor how you can answer thequestions under the section C++ Program Format in Lab 1.

    1.5 Checking your Program

    Now lets trace through the program by hand to see what will happen when we run it. Knowinghow to trace through a program is an important part of programming. It is stepping through theprogram and doing everything that the computer would do. We do this to make sure that weunderstand how the program is working and to ensure that it is working correctly.

    To trace programs, I use a piece of paper with a screen box (i.e., what will appear on thecomputer monitor), and a box for each variable. Thus, because the initial values of the variablesare not known, the initial setup of our hand trace is given in Figure 1.

    Screen:centimeters: ??inches: ??

    Figure 1: Initial Picture of InToCm program

    The first executable statement of the program is cout

  • Screen: This program converts inches to centimeterscentimeters: ??inches: ??

    Figure 2: Trace of program after first statement

    Screen:This program converts inches to centimetersEnter a number>

    centimeters: ??inches: 2.0

    Figure 3: Trace of program after third statement

    Calculate the trace after the next three statements and answer the questions under TracingPrograms in lab 1.

    After executing the return statement, the program returns from main to the operatingsystem. The values as well as the labels for the memory locations that held the values of inchesand centimeters are destroyed when the program is complete.

    1.6 Synthesis

    Most labs will have a synthesis section in which you will write a program based on what youlearned. There is, however, no synthesis this week.

    6

  • Laboratory 2 Errors, Executing Programs, Redirection, WritingC++

    2.1 Objectives

    In this lab, you will learn

    how to write a C++ program from start to finish what syntax errors are and how to fix them what logic errors are and how to identify them how to redirect input and output what batch and interactive programs are

    2.2 Correspondence to Text

    The material in this lab best corresponds to sections 2.6-2.8 in the text.

    2.3 Compiling and Running C++ programs

    Last lab, you examined a C++ Program, intocm.cpp. Lets look at it a little more.

    Compile your program, and run it. Your instructor will tell you how to do that. Enter 2.0 when the program asks you for a prompt, and hit the return key Print the source code file (our .cpp files are called source files or source code because they

    contain the source of the compilation C++ statements) because you may want to refer towhat a program should look like throughout this lab. Ask your instructor how to print filesif you do not know how.

    Since the actual running of the program matches our hand-trace, this means that theprogram ran successfully. It is rare that a program will compile and run successfully the first timethat it is tested. Lets look at some problems that can come up.

    2.4 Problem Solving

    Programming is really all about how to solve a problem. Some of the steps to problem-solvingare: 1) analyze the problem to determine the problem inputs, outputs, and constants; 2) developan algorithm that is, a list of steps to solve the problem (this step includes tracing through thealgorithm by hand as we did with the intocm.cpp program); 3) implement the algorithm thatis, write a C++ program to correspond to the steps in the algorithm (this step includes compilingthe program and removing syntax errors); and 4) test the program and remove any errors.

    7

  • Research has shown, especially when you begin to write larger programs, that the moretime that you spend on steps 1 and 2, the less time that you will spend on the total program (all4 steps). That is, although it doesnt seem that important now, developing a good algorithm andstructure chart (discussed in Chapter 3) will save you time in the long run.

    This lab is just going to concentrate on compiling and running programs, but this shouldbe done only after steps 1 and 2 have been completed.

    2.5 Correcting Syntax Errors

    You wont always have a program compile successfully on the first try.

    Copy the program trip.cpp into your directory or account. Ask your instructor if you haveforgotten how to do that.

    Examine the file. Compile the program.

    You should get an error listing similar to the following:

    trip.cpp:9: parse error before {trip.cpp:13: syntax error before trip.cpp:20: warning: ANSI C++ forbids declaration with no typetrip.cpp:20: abstract declarator int used as declarationtrip.cpp:20: distance was not declared in this scopetrip.cpp:20: speed was not declared in this scopetrip.cpp:22: syntax error before

  • use a temporary/usr/local/egcs/include/g++/iostream.h:216: warning: in passing argument 1

    of istream::operator >>(bool &)trip.cpp:18: parse error before

  • Lets test it once more using different numbers: 10mph and 40 miles (we know that it shouldtake 4 hours to do that). Run the program, and see what happens. This is the output youget: To travel at 10mph for 40 miles will take you 400 hours.

    WOW! Thats a long trip. The program seems to work only for selected data. It is importantto check your program with different data to make sure that it works with a wide varietyof data.

    Lets edit the program and see whats wrong. Look at the assignment statement.If you remember your physics, you know thatdistance = speed timeso if we are looking for the time, thentime = distance/speed

    We used the wrong formula! It just happened that our first test worked because the resultof multiplication and division were the same.

    Change the multiplication operator to a division operator (/) and save the file, and compileit.

    Test the file one more time with both test data sets (1 and 20 and 10 and 40). This timeyou should get the correct answer.

    2.6 Redirection

    Sometimes we want to enter data via the keyboard, but sometimes, it would be nice if we coulddo something else.

    Run the intocm program again. Use 2.0 as the test value.

    Running a program in this way is referred to as interactive because as the program isrunning, the user (i.e., the person running the program you) is entering data and getting feed-back. Not all programs are run this way. For example, a computer program probably calculatesyour paycheck. That program almost certainly does not have a user at the keyboard typing ininformation; instead, the program reads all of the information from a file (e.g., an employee filethat contains a list of all employees and what their pay rate is), and then at the very end printsout a list of paychecks. Unless something goes wrong with the payroll program, it probably doesnot interact with the person who initiated the program. This kind of a program is referred to asa batch program. It runs with no interaction from users.

    2.6.1 Input Redirection

    The advantage of a batch program is that the information does not need to be entered every timethe program is run the input can be kept in a file (imagine how many errors there would be andhow much time would be taken if somebody had to type in all employees names and pay ratesevery time checks were issued). Another advantage is that we can test a program over and overwithout having to enter the data each time. If the data is in a file, it just has to be entered once.

    10

  • So far, the amount of data (one number) that we have been entering is small, but it can get longand tedious to test a program that has a long list of inputs.

    We can put the input for a program in a file (e.g., a file named inputfile), and theprogram will read any input from the file instead of from the keyboard. On systems with acommand line interface (that is, you enter commands at a prompt), you can do this by typing:

    program out

    Redirecting the output is normally not used by itself if the input is going to be read fromthe keyboard.

    To see why, run intocm redirecting the output to the file cm. If using a command lineinterface, type:

    11

  • intocm >cm

    What happens? The program just sits there. Actually, its waiting for you to enter a numberof inches.

    Type 2.0 and hit the return key. You should get a prompt again. Because the prompts totell you what to enter went to the output file, it was difficult to know what to do.

    Look at the output file cm. Do you see the prompts there?

    Normally, programs that have their output redirected run completely in batch mode whereboth the input and output and redirected. When output is redirected to a file, it can be examinedlater for accuracy or it can be used as input for another program. Once the information is writtento a file, it is more permanent than information displayed on the screen and can be used for anumber of purposes. Run intocm again, redirecting both its input and its output:

    Type (if you are not using a command line interface, ask your instructor):

    intocm cm

    (If you get a message that cm already exists, remove the file cm, and then enter the commandabove again.)

    Look at cm to make sure you have the right answer. Lets see if you understand redirection. Answer the questions under the Redirection section

    of lab 2 questions.

    2.6.3 Redirecting Errors

    In addition to redirecting input and output, you can also redirect any syntax error messages thatthe compiler generates. It is often useful to have a file that contains all of your syntax errors.Ask your instructor how to do this on your system.

    2.7 Synthesis

    Now lets write a program. We want to write a program to convert feet to yards. First, of course,we need an algorithm. Fortunately, the algorithm is in the file that you have copied.

    For the actual writing of the program, you may want to refer to the intocm.cpp programas an example. Edit the program, and do the following:

    Copy the file feettoyards.cpp. First, add your name in the second line as a comment so that people know who wrote the

    program.

    12

  • Second, write a compiler directive to include the file iostream using earlier programs as anexample if you dont remember how to do this.

    Third, add the using namespace std; line to indicate that objects are in the standardnamespace.

    Next, write the program format in the program. That is, right after the line that says:// begin the program by writing the function main and the program format,write:

    int main (){

    The variable declarations will go immediately following the open curly brace.

    Put a close curly brace at the very end of the program after all other lines. This correspondsto the general format of a C++ program given earlier.

    Next, add the variable declarations for feet and yards under the lines// declare the variables that we will use:// feet will hold the input (of type float)// yards will hold the output (of type float)Make sure that you have a semi-colon at the end of the line that declares the variables.Name the variables feet and yards.

    Next, put a blank line separating the variable declarations and the executable statementsand start the executable statements.

    First, underneath the comment// write a statement about what this program does, write a statement to the user in-dicating what this program does: cout Next, write a cin statement to read in the number of feet into the variable feet. This onecomment covers two C++ statements. In general, you will not have one comment for everyline of C++ code. That would be distracting and hard to read exactly the opposite ofwhy you have comments in the first place!

    Look at the intocm.cpp file and see if you can tell how to read a value into the variablefeet based on how you read a value into the variable inches.

    After you have written statements to read in the data (which you did in the previousstep), write the necessary statement to do the calculation under the comment that says: //calculate conversion using formula yards = feet / 3

    Next, you will need to write the C++ code to output the answer. It is good programmingpractice to echo the input as I have in the intocm.cpp program; that is, when you write

    13

  • the answer (which in this case will be the number of yards) also write the input (which inthis case is the number of feet). I have written this cout command for you in a comment.All you need to do is remove the // at the beginning of the line.

    Finally, you should put return 0; as the last line in your main function. You have just finished writing your first C++ program. Now, compile it and run it. Test it

    using the following test data: 0.0 feet, 10.0 feet, and -3.0 feet.

    Make sure you understand how to write, compile, and run a C++ program because you willbe doing this process the entire semester.

    Now, create a file infeet that has just the number 10.0 in it. Run the program feetyards, and redirect the input to be from infeet, and redirect the

    output to be to a file called feetout.

    14

  • Laboratory 3 Expressions, Libraries, and Functions in C++ Li-braries

    3.1 Objectives

    In this lab, you will learn

    more about expressions and input how to use functions what C++ libraries are what functions are available in some C++ libraries more about writing C++ programs.

    3.2 Prerequisites

    You should know how to write, compile, and run a C++ program in order to do this lab.

    3.3 Correspondence to Text

    The material in this lab best corresponds to 2.4-2.6, 3.1-3.2, and parts of 3.5 and 3.7 in the text.

    3.4 Introduction

    You have already seen one function in all of the programs that you have written. That functionis main. But most programs have many other functions. And there are often functions andother information contained in header files also. You have also used header files in the past: the#include statement includes the header file called iostream, which includes C++code that allows you to use cout and cin.

    3.5 Input and Output

    Before we look at functions, lets look briefly at more input and output. In the programs thatwe have examined so far, we have only entered one value at a time. But cin, like cout can havea number of values on which it operates in one statement. For example, if we were trying tocalculate the area of a rectangle, we could do it by entering the length and the height one rightafter another.

    Copy the program recarea.cpp. Compile the program.

    15

  • Run the program. When the program asks you to enter the height and length, enter 3 and4 separated by a space.

    Now view the program. Notice how the cin statement reads one value after another. Also,notice that the data values are int and not float. We could have declared them as float,and used the same cin statement. I just wanted to give you an idea of how integer valueswork in C++ because the other variables that weve been using have mostly been of typefloat.

    Answer the questions in the cin section of Lab 3 Questions. Remember that the C++input stream operator is >> and not

  • 3.6.2 Order of Operations

    What happens when you have an expression that has several different operators? Which one doyou do first? For example in the expression (14 + 6) - 8 / 2, what is the answer? The order ofoperations for C++ is the same as the order of operations that you learned in your math class.From left to right in the expression, this is the order:

    1. First, expressions inside of parentheses are evaluated.

    2. Next, the multiplication operators (*, /, %) are performed.

    3. Finally, the addition operators (+, -) are performed.

    3.6.3 Practice

    Look at the following chart and make sure that you understand why each result is correct.

    Expression Resulting Data Type Result Notes10 % 3 int 110 / 3 int 3

    10.0 / 3.0 float 3.3333310.0 / 3 float 3.33333 (int 3 converted to float)

    3 / 4 int 03 % 4 int 3

    (3 + 4) / 6 - 2.0 * 8 float -15.0 order: 3 + 4 = 77/6 = 1

    2.0 * 8 = 16.01-16.0 = -15.0

    15.0 will be displayed as 15

    Answer the questions in the Evaluating Expressions section of Lab 3 Questions

    3.6.4 Expressions in Programs

    Lets write program to calculate the volume of a sphere. You may remember that the volume ofa sphere is: volume = 43pir

    3

    Copy the program sphere.cpp. This program is already written except the line that performs the volume calculation. Write

    in that line. Use 3.14 as the value of pi. Remember that dividing by two integers results inan integer answer. For now, just write r3 as r * r * r. Do not modify any of the cin or coutstatements or your output will not match mine when you test it later on.

    Test the program using the value 2.0. Your answer should be 33.4933.

    17

  • 3.7 Libraries

    We talked briefly in the first lab about compiler directives and the #include linein all of our programs. I want to talk about that more now, and what that means. Programmersare inherently lazy people, and do not like to do work twice. For that reason, programmers reusecode that already exists whenever possible. This reuse has many advantages. If a programmerthinks that a portion of C++ code is likely to be reused by the programmer or by others, thatprogrammer might want to save that portion some place where others can access it. Thesecommonly reused portions of C++ code are stored in libraries. A library is simply a file orcollection of files that contains C++ code that might be useful.

    3.7.1 Including Libraries

    You may create your own personal library, but libraries are also included with a compiler. In-cluding C++ code from a library into your own program is easy youve been doing it sincethe beginning of the semester. Just use a compiler directive called include to name the file(remember that all compiler directives start with the # symbol).

    Copy intocm.cpp (copy it again if you still have it from earlier labs). Edit the file. Delete the line that begins #include. Compile the file. What happens? You should get these errors (or a similar listing):

    intocm.cpp: In function int main():intocm.cpp:12: cout undeclared (first use this function)intocm.cpp:12: (Each undeclared identifier is reported only onceintocm.cpp:12: for each function it appears in.)intocm.cpp:12: endl undeclared (first use this function)intocm.cpp:14: cin undeclared (first use this function)

    These errors occur because the compiler cannot find the C++ code for cout and cin since thiscode is contained in the file iostream, and iostream is no longer a part of the C++ programintocm.cpp.

    Put the line #include back in the file intocm.cpp, and recompile it. Whathappens now? With the header file back in, the code for cout and cin is found again, andthe program should have no syntax errors.

    3.7.2 What is a library?

    Library files are files that contain compiled C++ code. They usually have header files associatedwith them (files which are read into your program with #include). Some standard C++ headerfiles are cmath, iostream, cstdio, and string. Each of these files contains C++ code that allowsyou to use code in your own personal programs that was written by somebody else. For example,

    18

  • if you wanted to calculate the value of some number cubed (i.e., x3), you could multiply thenumber by itself three times (x * x * x), but it would be nice if you could have had a function tocalculate x raised to the third power instead of writing x * x * x. There is a function called powin cmath that does just that. If we include cmath, then we can use the pow function instead ofwriting x * x * x. Many other useful functions exist in these header files as well. Your book listssome of the libraries available with most C++ compilers, including some of the functions that areavailable in cmath; and many functions that are available in different libraries along with otherrelevant information for that function.

    Examine Appendix C in your text which discusses these functions and answer the questionsin the section C++ Libraries of lab 3 questions.

    3.7.3 Whats in a header file?

    A header file contains no special code just standard C++ code. If you look at a header file, itmay look strange compared to the C++ code that youre used to seeing, but that is because wehavent learned some of the constructs used here; its not because there is anything mysteriousabout this code. The C++ libraries on one system are in /usr/local/egcs/include/g++ and/usr/include. Ask your instructor where your C++ header files reside.

    Look at the file cmath in the directory that contains the C++ libraries on your system.

    The very first line is a C++ comment. You can tell because it begins with the two symbols// There is some other stuff, and then the line: #include (Note that this include fileuses the .h extension, while others did not. This is because it is part of the Standard C library,not part of the Standard C++ library). This shows that header files can include header filesalso. The next couple of lines contains something close to variable declarations; float and longdouble are kinds of floating point numbers. You can look at other header files and you may seesome C++ code that you recognize. The point is that header files contain C++ code that youcould have written (or will be able to write eventually!).

    3.7.4 Creating a header file

    So why dont we write our own header file? Lets say that the variables inches and centimetersare much in demand, and will be required by many programs. We can put those variable decla-rations in a file by themselves.

    Since were going to put inches and centimeters in a file by themselves, take them out ofintocm.cpp. Edit intocm.cpp, and delete the line that says float inches, centimeters;(make sure that you leave the opening curly brace which begins that function main).

    Now, create a file called intocm.h Unlike system include files like iostream, your owninclude files should end in .h. Put the line: float inches, centimeters; in intocm.h.Save the file.

    19

  • Compile intocm.cpp. You should get the following syntax errors (or something close):

    intocm.cpp: In function int main():intocm.cpp:15: inches undeclared (first use this function)intocm.cpp:15: (Each undeclared identifier is reported only onceintocm.cpp:15: for each function it appears in.)intocm.cpp:16: centimeters undeclared (first use thisfunction)

    Why did that happen? It happened because we deleted the declaration of inches andcentimeters, and we didnt include the declaration any place else. Edit intocm.cpp, andadd the line:#include "intocm.h"immediately after the line #include . Note that you use quotation marks,and not angle brackets. Whenever you create your own header file, use quotation marks.This tells the compiler to look in your directory, not the standard include directories.

    Compile the file again, and run it. This time it should run just like it would have withoutthe changes.

    3.7.5 Using a Math Library

    Remember writing sphere.cpp? It would be nice if we could just use a value for pi that wasalready defined somewhere (like maybe, in a library), and if we could use the pow functioninstead of writing r * r * r.

    We can do that by including cmath in our file. Copy sphere.cpp to sphere2.cpp. Editsphere2.cpp, and add the compiler directive #include immediately after thecompiler directive #include (on separate lines).

    Change your value of pi (3.14) to be M PI. M PI is a constant in the file cmath. It is accurateto 20 decimal places 18 better than we just did!

    Change where you have written r * r * r to be pow(r,3) Compile the program. Run the program using 2.0 as a test value again. This time your answer should be 33.5103

    (the extra accuracy of pi is the reason for the difference).

    3.8 Functions

    In addition to reusing existing code, programmers also like to break problems down into subprob-lems. Subproblems are often implemented as functions in C++. Functions in C++ can performcalculations and return a value. For example, pow returns the value of a number raised to a power.When you used pow, you were calling or invoking a function.

    20

  • 3.8.1 Information for invoking functions

    Functions in C++ can have arguments. Remember that arguments to functions tell the functionwhat objects to use in performing its task. For example, in order to raise a number to a power,the function must know what the number is and what the power is. This information is passed tothe function in terms of an argument. When you typed pow(r, 3), you were telling the functionpow to calculate the value of r raised to the third power, and to return that calculated value.The value returned may be used as part of an expression (as it was in this case), or in any waythat a value of the return type can be used, e.g., as another argument to another function, (e.g.,log10(pow(100,2)) would return the base-10 logarithm of 1002, which is 4). Look in your bookin Appendix C. Look at the function pow. The information there says that pow has 2 argumentsthat are of type double (that is, a real number type like float). It also says that pow returns anumber of type double. Lets look at another example. The function isdigit has one argument,a character, and it returns an integer (0 if the character argument is not between 0 and 9, andsome non-zero number if the character argument is between 0 and 9 this part is not includedin the explanation in your book; I just knew that). So, isdigit(3) would return a non-zeronumber and isdigit(a) would return 0. You can see that the three pieces of information thatare critical when calling a function are: 1) the name of the function; 2) the number and typeof the arguments (if any); and 3) the return value of the function (if any). Note that not allfunctions have return values, and not all functions have arguments.

    3.8.2 Invoking Functions

    When you write your own functions, you will need to define the function and you will need todeclare the function (just like you declare variables). Well discuss how to define and declare afunction next week; for the functions that exist in libraries, the functions have already been definedand declared. To call a function, use the C++ code: name-of-function(arg1, arg2, ...argn) where name-of-function is the name of the function and the arg1, etc. in the parenthesesis the list of parameters. For example, you called the function pow by typing pow(r, 3) (r and3 were the arguments to the function). This example shows that the order of the argumentsmatters. pow(3, 4) is 81 (34); pow(4, 3) is 64 (43). Another example of calling functions is byincluding them in a cout statement. If you wanted to print whether the letter a was a digit, youcould include the statement cout

  • 3.8.3 Return Values for Functions

    Functions can be said to be of certain types. A functions type depends on its return value. If afunction returns a value of type int, then the function is of type int (int is in fact the defaulttype). If a function has no return value, it is void.

    Back to the functions that are in Appendix C in your book: function pow is type doublebecause the return value of pow is double. double is a type similar to float.

    Edit your file intocm.cpp, and include the statement cout

  • Because it takes a while to compile, it might be quicker, especially if were going to usepower.cpp over and over if we keep it compiled all of the time. Try compiling power.cpp.What happened? You dont have a main function. Do you remember when I told you thatevery program has to have a main function? But it still seems silly to compile it from scratcheach time its used. C++ allows you to compile separate object modules: intermediate fileswhich can linked, or combined, into one executable module.

    Compile power.cpp into an object file, not an executable file. Ask your instructor how todo this.

    You can now use this object code when compiling sphere3.cpp or any other source codefile that uses power.cpp.

    Compile sphere3.cpp with the object file created by power.cpp (it may be called power.o).Ask your instructor how to do this.

    3.10 Synthesis

    Write a program synthesis.cpp that reads in a base and an exponent, and that calculates andoutputs baseexponent. For example, if the user entered 10 for the base and 3 for the exponent, theprogram would output 1000 (which is 103). Use the function pow in cmath.

    Write and compile synthesis.cpp. Test the program. Test the program by running it at least twice, first with the numbers

    3.04 and next with the numbers 4.03.

    23

  • Laboratory 4 Writing Functions

    4.1 Objectives

    In this lab, you will learn

    how to declare functions what a function declaration is how to write a function what arguments and return values do and how to use them

    4.2 Prerequisites

    In order to do this lab, you should know how to write, compile, and run a C++ program, andyou should understand what functions are and how to invoke them. You should also be familiarwith an editor.

    4.3 Correspondence to Text

    The material in this lab best corresponds to 3.3-3.5 in the text.

    4.4 Introduction

    In the last lab, you learned how to invoke functions. In this lab, you will learn how to write yourown functions, and call them from other functions.

    4.5 Functions without Arguments or Return Values

    4.5.1 Writing Functions

    Breaking problems down into subparts, and putting the subparts into functions has many ad-vantages. The subparts can be reused several times in the same program or in other programs;they can be modified without changing any other part of the program; and the details of how thesubparts are solved are hidden from the higher level functions. One function that you might wantto have for any program that you write is a function that prints instructions to the user tellingthe user how to run the program.

    Copy restaurant.cpp. Look at the program to see the function instruct user. Thefunction is after the main function starting on line 33.

    24

  • 4.5.2 Examining the Function

    The first line of the function is:

    void instruct user ()

    This line is called the function header, and there is no semicolon at the end of the line.The function body is formed by curly braces; it looks just like the body of main (i.e., you canput the same things in a function body as you can put in main because main is a function). Theentire function function header and function body is referred to as a function definition.

    4.5.3 Prototypes

    Lets go back and look before main. After the include statements, you should see the followingline: void instruct user (); // function prototypeThis is called a function prototype; it declares the function just as variables are declared.It contains the return type of the function (void for this function; recall that void indicatesthat no value will be returned from this function) and the type of any of the arguments (nonefor instruct user). For every function definition, there should also be a function prototype.For many functions, however, the prototype (or function declaration) and definition are writtenoutside the main program file. This was the case for pow last week, for example. Both the functionprototype and definition were in other files. Look at the first line past the variable declarationsin the main function. This line, instruct user (); calls the function instruct user. This callis similar to calls to isdigit and pow from the last lab. The main difference is that there are noarguments in this call. Note that even though there are no arguments, there are still ()s.

    Answer the questions under section Functions without Arguments of Lab 4 questions.

    In addition to the main and instruct user functions, there is another function, calctotal inrestaurant.cpp. This function calculates the cost of a meal based on the cost of the food andthe beverage (15% tip and Virginia food tax of 9% are also included). Look at this function, anduse it as reference later when writing functions with arguments and functions that have a returnvalue.

    Compile and run restaurant.cpp. Use $9.00 for the price of food, and $2.00 for the priceof drinks (be sure to leave off the dollar sign when entering the numbers). Notice that theanswer is not displayed in terms of dollars and cents. It would be nice if we could roundthe answer off to the nearest cent as restaurants actually do. Chapter 5 discusses how to dothat. For now, well have to settle for too precise an answer.

    4.5.4 Writing Functions

    Lets write a similar function in another program.

    Copy the file balance.cpp.

    25

  • Add an instruct user function that is similar to the one in the file that you just examined.Edit the file, and add a function prototype, a call to the function, and a function definition.In the function definition, write instructions to the user on how to use this program.

    Save, compile, and test the program.

    4.6 Functions with input arguments

    If all we could do is write instruct user functions, functions would not be very useful. But youknow that functions can have inputs arguments as well that allow much more flexibility. You usedpow with several different input arguments last lab. Lets write our own function that has inputarguments. In this case, were going to write a function that outputs the message hi xyz wherex, y, and z are going to be input to the function. So, the same function can print Hi Mom,Hi Dad, and Hi Dog(this may not sound terribly exciting, but in fact, this capability offers agreat deal of power, especially when used with return arguments).

    Copy mom.cpp. Compile and run the program. Enter Dad at the prompt. Type the return key. Run the program again, typing Mom this time at the prompt. You can see that the program

    produces different output depending on the input.

    Now, look at the program. Examine the function prototype and the function definition. Write a second function, printbye that takes the same arguments and prints bye, xyz

    (where xyz are the three characters that you entered). First, write the function call imme-diately below the call to printhi in the main function. You do not need an additional cinstatement because you have already read in the data before the printhi call. After writingthe call to printbye, write a function prototype immediately following the printhi proto-type. Make sure that you understand what is calling the function and what is declaring thefunction. Finally, write the printbye definition, which should be identical to the printhidefinition except it should cout Bye instead of Hi. Remember that function headers donot have a ; at the end of the line, unlike function prototypes, variable declarations, andexecutable statements.

    Compile and test the program. Answer the questions under the section Functions with Arguments of lab 4.

    4.7 Functions with return values

    We still havent done functions that are terribly interesting for example, we still couldnt writepow or any other function that performs some kind of calculation because we havent talked aboutreturning values from a function. It is possible to return a value calculated in a function by using

    26

  • the return statement. For example, our beloved intocm.cpp program could be rewritten withthe calculation being performed in a function, and the result of that calculation could be storedin centimeters and returned to a calling program. Lets see how thats done.

    Copy the file intocm.withfunc.cpp into your directory. Compile it and test it. Look at the function prototype (float intocm(float);). This states that the function

    has one argument which is a type float (this is given in the parenthesis), and that it willreturn a value that is of type float (thats what the float before the intocm means).

    Look at the function header (float intocm(float inches)). It states that there is oneargument of type float, and the name of the argument inside the function will be inches(the calling function could call this argument a completely different name). The body ofthe function consists only of a return statement that returns a value of the type float.Functions can be much more complicated than this.

    Look at another example of a function. Copy distance.cpp. This program calculates thedistance between 2 points.

    Compile it. Test the program with several different points. Use (3,3) and (4,4) as one test and (4,10)

    and (14, 10) as a second test. When you enter the points, just enter numbers; do not enterparentheses or commas.

    Look at the two functions definitions, sqr and diff. They show that you can calculate thevalue, assign it to a local variable then return the value of the variable (as in sqr), or, ifthe calculation is a relatively simplistic one, the calculation can be performed in the returnstatement itself (as in diff). Write whichever seems the most natural to you, and the onethat you think is the easiest to read.

    You will notice that the program also has a statement about the slope of the line, but theslope is currently not being calculated correctly. Lets modify the program to find the slopeof the line. The equation for the slope of a line given two points (x1, y1) and (x2, y2) is:slope = (y2 y1)/(x2 x1)Modify distance.cpp so that it calculates the slope of the line as well as the distance.Modify only the one line that reads:

    // slope = put slope expression here

    Remove the comment, and put the correct calculation. You should use two function callsin your calculation; (there are five function calls in the distance calculation; from left toright, they are: sqrt sqr, diff, sqr, diff).

    Recompile and test the program. Answer the questions in the final set section of Lab 4 questions. Answer the questions in the Mixed Bag section of Lab 4 questions.

    27

  • 4.8 Synthesis

    Write a program tri.cpp that calculates the time that it will take to complete a triathlon. Atriathlon has three parts: a swim leg, a bicycle leg, and a running leg. There will be 4 constants inthe program: the swim length, the bike leg length, the run leg length; and the athletes transitiontime (transition time is the length of time that it takes to go from one leg to the other; thistypically involves putting on or taking off some clothes or equipment, such as a bicycle helmet).All lengths are in miles; the transition time is in minutes; and the pace/speed will be in miles perminute. In order to calculate the total time, you will ask the user/athlete for the athletes pace(all in miles per minute) for the swim, bike, and run (so you will have three inputs, all of whichwill be of type float). The total time is given by the formula:totaltimem = timem(swim)+ transition timem+ timem(bike)+ transition timem+ timem(run)

    That is, the total time (in minutes) equals the total time of the swim (which comes first,so people are fresh and dont drown) plus the transition time (from swim to bike) plus the totalbike time plus the transition time (from swim to run) plus the total run time. All times are inminutes (thus the subscript m). Because you are calculating the time to complete a particularpart three times, this part of the problem is an excellent candidate for a function. Therefore, youshould write a function, CalcLegTime, which takes the speed and distance of a particular leg asan argument and returns the time for that particular leg. For example, if a person bikes at 0.3miles per minute (thats 18mph) and the bike course is 14 miles, it will take about 47 minutes tocomplete that part of the course. In this case, CalcLegTime would have 0.3 and 14 as argumentsand would return 46.66... (14/0.3 or distance/speed). You should call this function three times:once to get the swim time, once to get the bike time, and once to get the run time. To getyou started, I have written a program shell that you may copy into your directory. It is calledtri.cpp.

    Copy tri.cpp. Write the function CalcLegTime and write the rest of the function main.The input and output statements are already written for you.

    Compile and test your program.

    28

  • Laboratory 5 Selection Statements

    5.1 Objectives

    In this lab, you will learn

    how to write and evaluate logical expressions how to write if statements how to write if-else statements how to write nested if statements how to hand trace if statements

    5.2 Prerequisites

    In order to do this lab, you should know how to write, compile, and run a C++ program, andyou should be able to call and write functions.

    5.3 Correspondence to Text

    The material in this lab best corresponds to sections 4.1-4.7.

    5.4 Introduction

    So far, the programs that you have written perform every statement. Problem-solving, however,often involves choices. In order to make decisions, programming languages provide some statementthat tells the system to perform some statement(s) if some condition exists and possibly someother statement(s) if that condition does not exist. For example, if we are making a cake, wecheck it after some amount of time. If it is done, we take it out of the oven. Otherwise, we leave itin the oven. If we are deciding what to wear in the morning, we check the weather. If it is warm,we wear short-sleeves; otherwise, we wear long-sleeves. If we were writing a program to choosethe larger of two numbers, we would choose the first number if it was greater than the second;otherwise, we would choose the second. In the constructs that we have learned so far, there is noway to express that.

    5.5 Logical Expressions

    In order to write the statements that allow us to make these decisions, we need to have some wayof evaluating the alternatives. Expressions that allow us to do this are called logical or booleanexpressions. Logical expressions evaluate to be either true or false. For example, to say that thevalue in x is greater than the value in y, we could write: x > y

    29

  • This expression would evaluate to be true if x is greater than y and false otherwise. 3 < 4is true (but 4 < 4 is false); 3 > 4 is false (4 > 3 is true); and 3 == 4 is false (4 == 4 is true); 3= 4 is true). The relational operators(i.e., the operators that compare values) are: , = and == for equals (do not confuse=, the assignment operator, with ==, the equal relational operator).

    Copy evaluate.cpp. Compile it. Run it to see what different expressions evaluate to be.You may use only numbers and the three relational operators , and ==. Do not use= For example, try 234 == 234. Would you expect this to be true or false?

    Try 234 == 5735, 253 < 1123, 2443 < 2245, 245 > 123 and any others to get the idea ofhow the expressions are evaluated.

    5.5.1 Compound Boolean Expressions

    Expressions can get more complicated than just using the relational operators. Sometimes it isnecessary to determine if a value is within some range. For example, to determine if a numberx is a single digit, it must be greater than or equal to 0 (x >= 0) and it must be less than orequal to 9 (x = 0) && (x 23) (x == y) true x > 23 is truex == y is falsetrue false is true

    c. !(x > y) false x > y is true!true is false

    d. !(x == 14) && (y < x) true x == 14 is falsey < x is true!false is truetrue && true is true

    Do the lab 5 questions in section Simple and Compound Logical Expressions.

    5.6 If Statements

    Logical expressions are great, but how do we use them in C++? C++ has an if statement thatallows the program to choose which statement to perform based on how a logical expression isevaluated. For example,

    30

  • if (grade >= 60)cout = 60 evaluatedto be false. I will refer to the part inside of the if statement (cout
  • 1)if (logical expression)

    statement;else

    statement;

    and2)if (logical expression)

    statement;

    We can modify the greatest program to assign x to be the greatest before any if statement, andthen assign y to greatest only if y > x.

    Copy secondif.cpp. Write the if clause associated with the if statement so that y is assigned to greatest wheny > x. Do not change any of the rest of the program.

    5.8 Compound Statements

    We can write if statements now, but what if we wanted to do more than one statement as part ofthe if clause or as part of the else clause. For example, we might have a program that calculatedthe area of different shapes. If you calculated the area of a rectangle, you would need the baseand the height as you would if you calculated the area of a triangle, but if you calculate the areaof a circle, you would need the radius, not the base and height. That program might have thefollowing code segment

    cout base;cout > height;

    Inside the else clause, you might want:

    32

  • cout > radius;

    I have written a program area.cpp that does exactly this.

    Copy area.cpp. Look at the if statement in the program. Compile the program. What happens? Why?

    You will get a syntax error because the else has no if to go with it. But why is that? Thereason is that only one statement is allowed inside an if clause and only one statement as partof an else clause. In order to have more than one statement as part of an if or else, we mustmake a compound statement. To make a compound statement, put an opening curly brace beforethe first statement, and a closing curly brace after the last statement. This should look familiar.This is what you do for all functions. The format of a function is the function header and thenthe function body which consists of a single compound statement (which may contain multiplesimple statements), that is:

    returntype functionname (function args)compound statement

    Edit the file area.cpp to make the statements inside the if clause one compound statementand the statements inside the else clause into one compound statement; that is, put curlybraces around the statements in the if clause and curly braces around the statements in theelse clause.

    Compile the program. Test the program using the choice T with the numbers 3 and 4; with the choice R with

    the numbers 3 and 4; and with the choice C and the number 2.

    5.8.1 Style Note

    It is important to adopt a consistent style of indenting, and use it in all of your programs to makethe programs clear. Always indent a couple of spaces on the line after an if and an else. If thestatement inside an if or else clause is a compound statement, all of the statements within thecompound statement should line up. There may be compound statements in only one of the if orelse clauses, or in both or in neither.

    Do questions under the section Simple and Compound If Statements in lab 5.

    33

  • 5.9 Nested If statements

    All of what weve done so far is great, but what if we want to check more than just 2 conditions.For example, we have calculated the greater of 2 numbers, but what if we wanted to output whichis the greater if they are not equal and that they are equal if they are. We could do it this way:

    if (x > y)cout

  • if (avspeed < 5)cout
  • // Grading.cpp// This program calculates grades on a 10 point scale

    #include using namespace std;

    int main (){

    char letter; // letter gradeint number; // number grade

    /* 1 */ cout

  • in the program. /* and */ is another way to write a comment.

    If we trace through the program, after the first line of the program, the variables number andletter are both undefined. Assuming that 87 is entered as the grade, after the fourth line,number contains the number 87, and letter still contains an undefined value. After line 4, thenext line executed is line 5, which checks to see if number is less than 0. If number were, thenprogram execution would proceed to lines 6 and 7 and then line 21 since line 21 is the nextstatement after the nested if statement starting on line 5. Because the input is 87 and not anumber less than 0, after line 5 is executed lines 6 and 7 are skipped; they are not executed. Thenext line to be executed is line 8.

    Answer the questions in the Tracing section of lab 5 which will continue tracing throughthis program.

    5.11 Synthesis

    Write a program that reports about 4 different programming teams: the Gazelles, the Grizzlys,the Gators, and the Giants. Your program will ask a person whether they want to know whichteam they play on (in which case they enter a W) or whether they would like to know whichteam they are playing next (in which case they enter an N). You will then ask the user for thefirst initial of the users last name. You can assume that the user will enter a valid initial (i.e.,a character between A and Z). If a W is entered for the choice, you will report which team theyplay on based on the users last name: If the first initial of the name is A-F, the user will playon the Giants; if it is G-L, the user will play on the Gators; if it is M-P, the user will play onthe Grizzlys; and if it is Q-Z, the user will play on the Gazelles. The function that does thisreporting, NameTeam will simply print the one word answer corresponding to the appropriateteam. If the choice is an N, you will use the users last name initial in the following way: Ifthe first initial of the name is A-F, the user will play the Gazelles next; if it is G-L, the user willplay the Grizzlys; if it is M-P, the user will play the Gators; and if it is Q-Z, the user will playthe Giants next. The function that does this reporting, NextOpponent will simply print the oneword answer corresponding to the appropriate team.

    You may run your instructors program which shows you how your completed programshould run. When you run the program, it will ask you to enter a W or an N to decide whetheryou want to know which team you are on, or what is your next opponent. Next, it will ask youto enter the initial of your last name. This must be a capital letter. Validation is not performedfor this part (because I do not require it for your program).

    Run the program. Ask your instructor how to do this. Try running it with W and L, Wand A, N and X, N and E and i (it wont ask you for an initial in this case). Makesure that it produces the correct answers.

    I have written the main function for this program. Copy the file teams.cpp. You onlyneed to write the two functions NameTeam and NextOpponent You must declare (i.e., give aprototype for) and define (i.e., write the function heading and body for) the two functions.Both functions are type void and both take one argument, a char which is the users

    37

  • initial. For consistency, the only thing that these functions should do is output one word:the appropriate team name in the function. Finally save, compile, and test teams.cpp.

    38

  • Laboratory 6 Basic Loop Control

    6.1 Objectives

    To be able to construct count-controlled loops. To be able to construct event-controlled loops. To be able to construct loops which perform common types of processing

    6.2 Prerequisites

    You should have studied the following topics in order to understand and complete the activitiesdeveloped here: writing C++ programs in general and the if statement in particular.

    6.3 Correspondence to Text

    The material in this lab best corresponds to sections 5.1-5.2, 5.4-5.5 and part of 5.3 in the text.

    6.4 Introduction

    You have studied one control structure that allows you to write C++ programs in which not everystatement in the program is executed sequentially: the if statement that allows you to writeprograms that make decisions about which statements to execute. There is one more generalclass of control structures: loops. Loops allow you to perform a statement more than one time(if the statement is a compound statement, you may perform a set of statements more than onetime). Loops commonly have the format shown below

    initialize loop conditioninitialize loop processingwhile condition is true

    update processingupdate condition

    For example, consider the following loop which finds the maximum of n numbers:

    // assume that n is 3/* 1 */ count = 1;/* 2 */ max = -9999; // a small number so all numbers

    // are greater than initial value/* 3 */ while (count number;

    39

  • /* 6 */ if (number > max)/* 7 */ max = number;/* 8 */ count = count + 1;

    }

    This loop finds the maximum of three numbers.

    Copy max.cpp. Print, compile and run the program.

    Only the loop and loop initialization lines are numbered. This program starts by doing all of thelines up to the line marked line 3. At line 3, the program evaluates the logical expression insidethe parentheses. If the expression evaluates to be true, the statement inside the loop (usuallya compound statement) is performed; otherwise, the first statement after the loop is performed(which in this case is a cout statement). It is possible that the statements inside the loop arenever performed (if the logical expression initially evaluates to be false). The loop condition (thelogical expression after the word while is called the loop condition) should be written so thatit will become false at some point so that the loop is terminated at some point. Often, somestatements before the loop are required to set up the loop. In this case, line 1 initializes theloop condition because it sets the variable count to 1. Thus line 1 performs the initialize loopcondition function. The loop itself will perform some function for which initialization is also oftenneeded. In this case, that is done by line 2 which initializes max to be some low number so thatany other number will be greater than the number read in. Thus line 2 performs the initializeloop processing function. Within the loop, any number of operations may be performed. Thereis always, however, some statement(s) which perform the processing the reason that the loop isbeing done; in this case, that reason is to find the max number. Line 5 updates the processingin this loop because it reads in number that is later (in the next line) used in processing. Line8 updates the condition because it adds one to count which is used in the loop condition todetermine whether the loop should be entered again.

    Answer the questions in section Loops in lab 6 questions.

    6.4.1 Infinite Loops

    One common problem that people have is writing a loop that never ends. This is referred to as aninfinite loop. The way to avoid infinite loops is to make sure that your loop condition comes closerto ending every time you go through the loop; that is, make sure the loop condition will eventuallybe false. For example, the loop in max.cpp comes closer to being false each time through the loopbecause count comes closer to being >= n each time. The first time through the loop, count is1, but it increases each time while n stays the same; thus eventually, it will no longer be the casethat count

  • Copy max.cpp to noend.cpp Modify line 8 to be:/* 8 */ count = count - 1;(that is, change the + to a -). Now, count keeps getting smaller, so the loop condition getsfurther and further away from being false. This will result in an infinite loop: count willstart at 1, then be 0, then -1, then -2, etc. count will always be
  • Modify the program to go through the loop 10 times. Compile and run the program. Answer the questions in section Sum 10 times of lab 6 questions. Copy sum1.cpp to sum2.cpp, and modify it to read in the number that the program should

    sum to. That is, instead of assigning the value of n within the program, you will read in thevalue of n. You should add the statement: cout > number;

    If you would like to see how this program should run, ask your instructor how to do that.

    Save, compile, and test sum3.cpp.

    6.4.3 Event-Controlled Loops

    The loop in max.cpp and sum1.cpp is called a count-controlled loop because the number oftimes that the loop is performed is some specific number (i.e., you can count the number of timesthat the loop will be executed). This is in contrast to an event-controlled loop in which thenumber of times that a loop will be performed is unknown; what stops the loop is that someevent happens. For example, consider the loop below, which finds the max of numbers until 0 isentered.

    /* 1 */ cout > number;/* 3 */ max = -9999; // a small number so all numbers

    // are greater than initial value/* 4 */ while (number != 0)

    {/* 5 */ if (number > max)/* 6 */ max = number;/* 7 */ cout > number;

    }

    42

  • This loop stops not after a certain number of times, but after the number 0 is entered. This0 is called a sentinel, and this kind of loop is called a sentinel-controlled loop because numbersare entered until some sentinel is entered that stops the loop. There are several things to noticeabout sentinel-controlled loops. The condition initialization usually consists of reading in thevariable that is in the loop condition immediately before the loop is reached so that there is someinitial value when the loop condition is reached. This is performed in lines 1 and 2 above. Theloop body itself usually consists of the processing (lines 5 and 6 in this case), and then the readfor the next number (lines 7 and 8). So the last statement in a sentinel-controlled loop (andmost other event-controlled loops) is generally a cin statement. This form is typical for mostsentinel-controlled loops.

    Copy the file max2.cpp. It contains a program with the above loop. Compile and test this program. It finds the maximum of all numbers until a 0 is entered.

    0 is not considered in computing the max. Test this by entering all negative numbers (butmake sure theyre all greater than -9999). If 0 were considered, the maximum number wouldbe 0, but it is not it is the largest negative number that you entered.

    Copy sum3.cpp to sum4.cpp. Modify sum4.cpp to add numbers until a -1 is entered. Do not add -1 in the summation. Save, compile, and test the program.

    6.4.4 Validation Loops

    One common use for a loop is to enter numbers until a valid number is entered. For example, inthe Telephone program last week, if the user entered something other than A-Z (except Q), theprogram stopped and gave the user no information. A more helpful program would have told theuser what the user had done wrong, and allowed the user to continue.

    Copy the program valtele.cpp.

    The section that last week was:

    if ((letter < A) || (letter > Y))cout

  • (I have also converted lower case letter to upper case letters so that if the user enters a lowercase letter, that will be considered valid, and the number corresponding to that letter willbe output just as it is for upper case letters). The point of the validation loop, as opposedto the if statement is that the loop is continually reentered as long as invalid data is en-tered. An if statement is only executed once; loops are executed as many times asthe user enters invalid data. The rest of the program is the same as the version last week.

    Look at the source code and compile and run this program with valid and invalid numbersto ensure that you can write validation loops. Enter more than one invalid number duringthe same run. What happens?

    6.5 Synthesis

    Write a program to find the product of two numbers that the user inputs, x and y, by adding xto itself y times. For example, if you wanted to find the product of 3 and 4, you would add 3 +3 + 3 + 3. This will only work if the second number is greater than or equal to 0 (though youcould make it work if the second number were negative, we will not do that in this lab), so youmust validate the second number to ensure that it is not a negative number. You will need towrite two loops: one that validates the second input, and one that performs the multiplication.The multiplication loop should be a count-controlled loop similar to the sum.cpp programs. Youshould have a variable in which the sums are accumulated and a counter that starts at one; theloop should end when the counter is greater than or equal to the second term (so that the loop isentered exactly y times). Your program run should look like this for the numbers 4, -4, -20 and20:

    This program multiplies two numbers togetherEnter the first number 4Enter the second number -4The second number must be nonnegative. Enter a number again, please -20The second number must be nonnegative. Enter a number again, please 20The product of 4 and 20 is 80

    Write, compile, and test the program.

    44

  • Laboratory 7 Debugging

    7.1 Objectives

    To be able to put debugging statements into a program. To be able to detect and correct logic errors in programs. To understand functions better.

    7.2 Prerequisites

    You should know how to write a loop before you start this lab.

    7.3 Correspondence to Text

    This lab does not correspond well to an exact section in the text, but sections 2.8 and 5.9 coversome of the material in this lab.

    7.4 Introduction

    So far we have written many programs, but if the program doesnt work the first time, there hasbeen no way to determine what went wrong. This lab will give you several hints for how to debugyour programs, but the best method is still careful design and tracing through your programbefore beginning your coding.

    7.5 Syntax Errors

    The first kind of error that you might run into when programming is syntax errors. Findingsyntax errors is a matter of a lot of experience in some cases, but also paying close attention tosyntax error messages. If the message says parse error, line 30 that means that somewhere onor before line 30 there is an error that prevented the compiler from translating the C++ codeinto object code. Lets look at a program full of syntax errors and try to figure out some of theproblems.

    Copy lab7.cpp. lab7.cpp is the triathlon program that we wrote in one lab. Compile the program.

    You should get errors similar to the ones below:

    lab7.cpp:34: unterminated string or character constantlab7.cpp:23: possible real start of unterminated constant

    45

  • This message usually means that you have forgotten an end quote. But the error message is alsotelling you that it found the end at line 34, but that it may have started at line 23.

    Find the missing end quote, fix it, and recompile.

    Now, depending on what compiler you use, you might actually get more errors than you hadbefore. This is because some errors mask other errors; that is, because the C++ compiler waslooking for an end quote, it skipped over some of the other errors. You should see somethingsimilar to the following error list now:

    lab7.cpp: In function int main(...):lab7.cpp:22: no match for _IO_istream_withassign &

  • Run temp, and enter 32.0 and A to convert the temperature 32.0 degrees F to 0 degreesCelsius.

    Copy the files temp.cpp, heat.cpp, and heat.h.heat.h is a header file that contains the declarations for the function definition containedin heat.cpp. These two files together are a library the header file and the implementation.The heat.cpp must be compiled separately from your file (temp.cpp). This is so thatthe heat library can be reused by many programs (just as you reuse iostream and math inmany programs).

    Compile the library into object code. Refer to the directions that your instructor gave youfor lab 3 for how to do this. After compiling, you should have an object file possibly namedheat.o which will remain in your library for linking (possibly with other object files) later.The process of linking will create an executable file.

    Compile and link your source with the heat.o file (or whatever your object file is called).Your instructor will tell you how to do this. You may then run your program; it shouldperform in the same way as the temp that you ran from the public directory.

    Run it and use the same values. You should get the same answers.

    7.6.2 Finding the problem

    This program looks as if it runs correctly. In fact, I took this program directly from a textbook(not yours), so one would think it would run correctly. However, there is an error in it. Your goalduring this lab is to find the error and fix it.

    Test all of the options with the values 32.0F, 0.0C, and 273K. All of these should beequivalent. Test all six options and determine which are incorrect.

    Answer the questions under section Checking Conversion in lab 7 questions.

    7.7 Debugging Statements

    7.7.1 x is 0 debugging statements

    There are many ways to find an error. Tracing through a program by hand is one of the best.Weve done that before. In this lab, we will use cout statements to help debug programmatically(by adding statements in the program itself). It is also often useful to know exactly where youare in the program and the value of variables at a particular point in a program. This techniquemight help us debug the temperature program that we have. There are two conversions that aredone incorrectly: C and D. There are several reasons that the output could be incorrect. One ofthe following must be true: The output could be incorrect because the input is read in incorrectly;because the values are being passed to the functions incorrectly; because the calculation in thefunction is being done incorrectly; because the value is being passed back from the function

    47

  • incorrectly; or because the value is being corrupted after it has returned from the function. Tocheck each of these, we will add cout statements at various points in the program to locate theproblem.

    Copy the program heat.cpp to heat2.cpp and temp.cpp to temp2.cpp so that you donot destroy your old versions. This is a good debugging tip. When you start to debug aprogram, do not modify the original. Instead, copy it to another name, and modify the newfile. Now, youll modify heat2.cpp and temp2.cpp until you find the problem; then, youllgo back and fix heat.cpp and temp.cpp.

    Check the if clauses for c and d in the function Convert (in the file temp2.cpp) to ensurethat the right functions are being called. Add a statement in these clauses to display thevalue of the returned expression. To do this, assign the value returned to a variable tempthat you declare in the function Convert. Within the if clauses, you will need to add curlybraces since youre making a compound statement. The code should now be:

    float Convert (float Temperature, char Conversion){

    float temp; // for debugging purposesonly

    Conversion = toupper(Conversion);if (Conversion == A)

    return FahrToCelsius(Temperature);else if (Conversion == B)

    return CelsiusToFahr(Temperature);else if (Conversion == C){

    temp = FahrToKelvin(Temperature);cout

  • Next, edit heat2.cpp, the functions FahrToKelvin and KelvinToFahr. First, display theinput value (maybe its not getting passed correctly). Next, display the value that is be-ing returned (maybe the calculation is being done correctly, but its getting passed backincorrectly). Finally, lets perform the calculation in a different way (maybe the calculationis being done incorrectly). When converting from Kelvin to Fahrenheit temperatures, wecould do the conversion from K to C then from C to F. Lets cout that also. So, the functionKelvinToFahr in heat2.cpp should now be:

    {// the next statement ensures that the value was input and passed correctlycout

  • C - to convert Fahrenheit to Kelvin.D - to convert Kelvin to Fahrenheit.E - to convert Kelvin to Celsius.F - to convert Celsius to Kelvin.

    Your Choice ? DThe beginning value in Kelvin to Fahr is 273The ending value is 1014.8The celsius equivalent is 0The Fahr equivalent of that is 32D: Value returned is 1014.8

    -- The converted temperature is 1014.8.

    Your output may be slightly different because your couts may be slightly different. How-ever, you should have the same numbers, and should be able to figure out the problem based onour debugging statements. Remember, there is a limited number of possibilities for the problem.It is one of the following: The output could be incorrect because the input is read in incorrectly;because the values are being passed to the functions incorrectly; because the calculation in thefunction is being done incorrectly; because the value is being passed back from the function in-correctly; or because the value is being corrupted after it has returned from the function. Wevechecked each of these.

    Find out what the problem is, and fix it. Go through the same process for testing the C option, converting Fahrenheit to Kelvin. Fix the Fahrenheit to Kelvin problem. Save the program, recompile it, and test it. Modify the original program, recompile it, and test it. In heat.cpp and temp.cpp (the

    original files), do not use any additional cout statements; we added these just to figure outwhere the problem was. Now that you know that, just fix the problem.

    7.8 Synthesis

    Copy the program lab7end.cpp. Name it the same thing in your directory. All this programdoes is perform several calculations. The program reads in two numbers (x and y) andcalculates: x2 x! + xyx! is read x factorial and is an abbreviated way of writing: x * (x-1) * (x-2) * (x-3) * ...* 2 * 1. For example, 4! = 4 * 3 * 2 * 1 = 24. Thus, if x were 4 and y were 5, the equationwould be: 42 4! + 45 = 16 24 + 1024 = 1016.

    Copy the program to another name as well (e.g., lab7end2.cpp). There are two logic errors.There is nothing wrong with any of the variable types (i.e., all ints should remain ints and

    50

  • all floats should remain floats). One note about types: this program has many variablesof type double. This is simply a type of float. When you see it, think float (you caneven change them all to floats if you want, and the program will still work correctly onceyouve fixed the logic errors which have nothing to do with the types of the variables or theparameters).

    Add cout debugging statements to lab7end2.cpp, and compile and test lab7end2.cppuntil you have found the errors. You might also find it helpful to hand trace the programto find the errors (getting a printout of the file may help you do this).

    Fix the errors and test lab7end2.cpp. Fix the errors in lab7end.cpp, and compile and test it. There should be no debugging

    statements in it, but the errors should be corrected.

    51

  • Laboratory 8 Review of Functions and Parameters

    8.1 Objectives

    To understand functions and parameters better

    8.2 Prerequisites

    You should understand how to call, declare, and write functions.

    8.3 Correspondence to Text

    The material in this lab best corresponds to sections 3.3-3.5, 3.8 and 6.1-6.4 in the text.

    8.4 Introduction

    In this lab, we will practice using functions and parameters. There are two kinds of parameters:value and reference. Value parameters copy the value of the calling parameter to the calledfunction. Reference parameters do not copy the actual parameters value, but instead create apointer from the formal parameter to the actual parameter. Whenever the formal parameterappears on the left hand side of an assignment statement, the value that is changed is the actualparameter since the formal parameter points back to the actual parameter.

    Functions have types. The type of a function is its return value. Some functions have noreturn value; their type is void.

    8.5 In, Out, In-Out Parameters

    Parameters can be categorized into three classes: In, Out, and In-Out. For every parameter inevery function that you write, you need to decide what kind of parameter you are dealing with.In parameters are those that have a value when the function is called. This value is used by thefunction, but it should not be changed when the function is done. Out parameters are those thatwhose initial value is not used by the function, but the parameter gain a value during the courseof the function so that when control returns to the calling function, the actual parameters havedifferent values than before the function was called. In-Out parameters are a combination of inand out parameters. The value of the parameter when the function begins is used in the function,and the value of the parameter is changed during the function so that when control passes backto the caller, the actual parameters have different values than before the function was called.

    Answer the questions In and Out in lab 8.

    52

  • 8.6 Value Parameters

    You want to use a value parameter when the parameter is going to be used, but not modifiedduring the function.

    For example, you might want to print a series of values.Copy printvals.cpp. This function is a variant of the intocm.cpp program that you havealready seen.

    Add the function prototype and function header for writeanswer. This function prints outthe answer. The actual parameters, inches and centimeters are value parameters becausetheir value does not change as part of the function, but the values are used in the function.

    Copy cube1.cpp. This program cubes a number, and prints the result inside a function. Write the function call, the function header, and the function prototype for this function.

    This function is not as natural as the previous function. It both calculates and prints thecube. In general, functions that perform two tasks probably need to be broken up.

    Finally, lets try to use a value parameter in a function that reads in a valid value. Copyread.cpp.

    Write the function call, the function header, and the function prototype for this function.Use value parameters.

    Test your program. Does it work? Why not? Answer questions read.cpp in lab 8.

    8.7 Reference parameters

    As you can see from the previous section, value parameters prevent functions from returningvalues in their parameters. When it is necessary to modify an actual parameter, the parametermust be passed by reference. To do this, place an & before the parameter in the function prototypeand in the function header. Reference parameters do not change the way functions arehandled within the function or in the function call.

    Modify read.cpp so that it works correctly. Compile and test the program. Copy swap.cpp. This program swaps two values. That is, the parameters in function swap

    both start with values, and their values are changed in the function.

    Answer questions swap question in lab 8. Write the function call, the function header, and the function prototype for this function.

    Compile and test the program.

    53

  • Lets try one more. Copy program sortc.cpp. This program sorts three input characters.If c, a, b is entered, a, b, c will be output.

    Answer questions sort question in lab 8. Write the function call, the function header, and the function prototype for sort, and the

    function header and prototype for function swap.

    8.8 Return values

    We have not dealt yet in this lab with functions that return values.

    Instead of sorting three characters, maybe we would like to find only the minimum valuefor the three. We could use sortc.cpp to do that, but it does more than we need. Copymin.cpp.

    Notice that rather than returning the minimum value in a parameter, we now return theminimum value in the function itself. Whenever a calculation is being performed, it is agood idea to return the result of that calculation in the return statement of the function.

    Write the function prototype, the return statements and the function header for findmin.

    Compile and test the program. Answer questions findmin question in lab 8. Earlier in the lab, you wrote a cube function, but I mentioned that it wasnt the best way

    to write a function because it did two things, a calculation and a print.

    Copy cube2.cpp. This version is much nicer because the function cube does only one thing:the calculation.

    Write the function prototype, the function body (including the return statement), and thefunction header for the function cube.

    Compile and test your program. Functions are often used as conditions in if and while statements: when a 1 is returned,

    the condition is true; a return value of 0 indicates the condition is false (sometimes, thesefunctions return values of type bool rather than int). Copy the program iswheel.cpp.This program has a function that determines if the character entered is one of the Wheel ofFortune letters: r, s, t, l, n, or e. I have made the input an upper case letter to simplify thefunction.

    Write the function prototype, the rest of the function body including the return statement,and the function header for iswheelletter.

    Compile and test your program.

    54

  • 8.9 Synthesis

    Write a program that calculates how much a tuition hike would cost. I have written the mainprogram for you. You only need to write the program prototypes, return statements, some callsand the function headers.

    Copy program tuition.cpp. Write all of the function prototypes and headers, and write the calls for getincrease andgetcurrenttuition, and the return statement for calcincrease.

    Compile and test the program.

    55

  • Laboratory 9 I/O Streams

    9.1 Objectives

    To be able to use input and output streams more effectively To be able to read and write to files using fstreams

    9.2 Prerequisites

    You should know how to use cout and cin to do this lab. You should also understand value andreference parameters.

    9.3 Correspondence to Text

    The material in this lab best corresponds to sections 8.1-8.6 in the text.

    9.4 Introduction

    This lab allows you to explore the output and input streams in more depth, and gives you someexperience reading and writing from files.

    9.5 Streams in Files

    Any collection of characters in C++ can be considered a stream of characters. C++ allows us toread and write files without having to use redirection (this is helpful especially if more than onefile is being read from or written to).

    9.5.1 Looking at file streams

    Copy the file countvowels.cpp.This program contains function parameters that are passed by reference. You will not needto use this information directly in this lab, but you should understand how these parametersdiffer from value parameters.

    This is a relatively complicated program. It may help you to print it out.

    The main function is what I want to talk about first. First, notice that there are twostrings, named infilename and outfilename. We have used strings before, but you may neverhave initialized them. C++ allows you to initialize many objects (that is, variables that are atype of class as opposed to a built-in type like ints) by putting the initial value(s) in parentheses;this is actually a function call as you will see later in the semester. For now, all you have tounderstand is that two objects have been created: infilename has the initial value "infile";

    56

  • outfilename has the initial value "outfile". It is possible to change initial values, but we wontdo that in this program.

    Getting back to file handling: In order to read and write files from a file instead of thereading from the keyboard and writing to the screen, five parts of the program must be modified.

    1. You must include fstream which allows you to read and write file streams.

    2. You must declare as variables any input or output file streams that you are going to use.To do this, use the type ifstream for any input files (i.e., files from which you will readonly), and type ofstream for any output files (file that you will write to). Look at programcountvowels.cpp to see how I did this in main.

    3. You must open any files that you are going to use. To do this, you will use the name ofthe file variable, a dot (period), and the name of the function (i.e., open in this case). Thefunction open requires one argument: the name of the file on disk. So, if the file variableis outfile, an ofstream or output file, and the name of the disk file to be created isvowelcount, you would open the file with the line:

    outfile.open("vowelcount");

    This would create a file name vowelcount, and write all information that is written to thevariable outfile to this file.

    Similarly, to open a file for reading, if the ifstream variable name is infile and the nameof the file on disk is infile (note that file and variables names do not need to be the samename, but they can be), you would open the file with:

    infile.open("infile");

    4. The files can be read from and written to just as cin and cout are read from and writtento. To read a character into a variable named inchar from a file with the ifstream variablename of infile, type:

    infile >> inchar;

    just as you would have typed cin >> inchar to read from the keyboard into charactervariable inchar. Only the stream name is changed. Similarly, writing to file streams isaccomplished just as writing to the output stream cout is accomplished. Examples ofreading from and writing to file streams are in function reportvowels.

    Notice that when file streams are passed as parameters, they are always passedby reference.

    5. Close all files. This is done just as opening files is done except that the function name isclose instead of open, and there are no arguments required. An example of this is in thefunction main.

    57

  • 6. Most input files (files that are being read) have an end of file check. In countvowels.cpp,the end of file check (in function reportvowels), is:while (!infile.eof ())

    This is typical. This while statements says to keep reading until the end of file marker isread. Once the end of file marker has been read, the condition in the while loop becomesfalse (0) and the loop is exited.

    The format for an end of file check is: .eof()(with no arguments).

    Do the questions section Files in lab 9. Copy the file infile, and compile and test countvowels.cpp to see what it does (infile

    is an input file for countvowels.cpp).

    Look at the output file to see what it looks like.

    9.5.2 Writing your own program

    Write a program to count the number of letters, and the number of digits from an input fileincounts Write the output to a file named: outcounts. I have started the program for you. Itis called lab9.cpp. Copy it into your account.

    Copy the file lab9.cpp into your directory. Add the five parts for each file (the include file, the variable declarations, the opening, the

    reading and writing, and the closing). You will also need to add an eof file check. Look atcountvowels.cpp to see how that is done. The file is commented with where these shouldgo.

    Copy the file incounts. Save and compile and test the program. This will create an output file outcounts.

    9.6 Getting precise about how data is read and written

    Sometimes, you might want to format your output or read your input differently than C++ doesautomatically. C++ has several ways that you can do this. It is not necessary for you to memorizeall of the different options because there are many. Output flags are discussed in Section 5.3 andSection 8.5. There are also flags for input that specify the way that input will be read. These arebriefly discussed in Section 8.5, and you will come across them as you need them.

    9.6.1 In


Recommended