c++ documentation tplo 16-02-09 - university of oxfordbrisbane/…  · web view · 2009-02-16this...

198
Programming: C++ introduction Oxford University Computing Services

Upload: hakiet

Post on 21-Mar-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

Programming:

C++ introduction

Oxford University

Computing Services

Page 2: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

How to Use this User GuideThis handbook accompanies the taught sessions for the course. Each section contains a brief overview of a topic for your reference and then one or more exercises.Exercises are arranged as follows:

A title and brief overview of the tasks to be carried out;A numbered set of tasks, together with a brief description of each;A numbered set of detailed steps that will achieve each task.

Some exercises, particularly those within the same section, assume that you have completed earlier exercises. Your teacher will direct you to the location of files that are needed for the exercises. If you have any problems with the text or the exercises, please ask the teacher or one of the demonstrators for help.A number of conventions are used to help you to be clear about what you need to do in each step of a task.

In general, the word press indicates you need to press a key on the keyboard. Click, choose or select refer to using the mouse and clicking on items on the screen.Names of keys on the keyboard are enclosed in angle brackets; for example <ENTER> represents the Enter (or Return) key.Multiple key names enclosed in angle brackets and linked by a + (for example, <CTRL+Z>) indicate that the first key should be held down while the remaining keys are pressed; all keys can then be released together.Where two or more keys are each enclosed in separate angle brackets (for example, <HOME><HOME><UP ARROW>) each key in the sequence should be pressed in turn.Words and commands typed in by the user are shown like this.Labels and titles on the screen and button names are shown like this .Drop-down menu options are indicated by the name of the option enclosed in square brackets, for example File | Print. To select the option Print from the File menu: click with the mouse button on the File menu name; move the cursor to Print; when Print is highlighted, click the mouse button again.A button to be clicked will look like this .The names of software packages are identified like this, and the names of files to be used like this.

OUCS ii Feb 2009

Page 3: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

Software UsedDev-C++

Files UsedArray.cpp InsertionSort.hArray.dev LinearSearch.cppCharNumString.cpp LinearSearch.devCharNumString.dev MultiDimArrayMain.cppCharNumStringFunc.cpp OverLoadingFunctions.cppCharNumStringFunc.dev OverLoadingFunctions.devconstructor.txt PointerArithmetic.devDoWhile.dev PointerArithmeticMain.cppDoWhile.h Pointers.devDoWhilemain.cpp PointersMain.cppFunctionTemplate.dev StudentMarksInterface.hFunctionTemplate-Maximum.cpp StudentUG.txtFunctionTemplate-Maximum.h TemperaturesRetValues.cppGetSet.txt TemperaturesRetValues.devHeader.cpp Vector.cppHeader.dev Vector.devIf.dev Vector.txtIfMain.cpp While.devIfSwitch.cpp While.hIfSwitch.dev WhileMain.cppIfSwitch.h

Revision Information

Version

Date Author Changes made

1.0 26 November 2005

Ian Miller Created

1.1 8 August 2006 Ian Miller Updates1.2 25 October 2006 Ian Miller Updates1.3 21 May 2007 Ian Miller Updates1.4 16 Feb 2009 Ian Miller Updates

CopyrightThe copyright of this document lies with Oxford University Computing Services.

Feb 2009 iii OUCS

Page 4: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

Contents1 Introduction................................................................1

1.1. What you should already know..........................................11.2. What you will learn............................................................11.3. Where can I get a copy?....................................................1

2 Things to understand.................................................22.1. Compilers, new and old.....................................................22.2. The C++ Standard Template Library (STL)......................2

3 Object Oriented Programming (OOP)........................33.1. Object Oriented programming Concepts...........................3

4 Installing Dev-C++.....................................................44.1.1. Installing Dev-C++..............................................................4

Exercise 1 Installing Dev-C++...............................................4

5 Creating your first program.....................................115.1.1. Creating your first program in Dev-C++..........................11

Exercise 2 Creating a first program.....................................115.1.2. What does this first C++ program do?.............................12

Exercise 3 Modify the program............................................145.1.3. Arithmetic Operators.........................................................165.1.4. Other fundamental data types:..........................................165.1.5. Characters.........................................................................165.1.6. strings................................................................................175.1.7. Casts..................................................................................18

Exercise 4 Create additional projects...................................19

6 Introduction to Functions.........................................226.1.1. Creating a function............................................................22

Exercise 5 Examining a function..........................................23Exercise 6 Writing functions.................................................26

6.1.2. Functions and Pass by Reference......................................29Exercise 7 Pass arguments by reference..............................30

7 Classes and Objects..................................................327.1.1. Creating your first class....................................................33

Exercise 8 Creating a class...................................................337.1.2. Member functions and Passing parameters......................35

Exercise 9 Passing parameters.............................................35

OUCS iv Feb 2009

Page 5: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

7.1.3. Data Members...................................................................35Exercise 10 Using data members...........................................36Exercise 11 More Objects.......................................................37

7.1.4. Constructors......................................................................38Exercise 12 Using constructors..............................................39

7.1.5. Destructors........................................................................407.1.6. Separate Class Files for Reusability..................................42

Exercise 13 Using header files...............................................42

8 Basic Control Flow...................................................458.1.1. Selection - if…else statement............................................45

Exercise 14 if …else selection................................................468.1.2. Selection - switch multiple selection statement................48

Exercise 15 switch selection...................................................488.1.3. Repetition – while, do…while and for loops......................52

Exercise 16 while loop............................................................52Exercise 17 for loop................................................................56Exercise 18 do…while loop.....................................................57

9 Arrays, vectors and lists...........................................589.1.1. Declaring and using arrays...............................................58

Exercise 19 Creating an array to hold exam results...............599.1.2. Searching Arrays with Linear Search...............................62

Exercise 20 Linear Search......................................................629.1.3. Sorting Arrays with Insertion Sort....................................65

Exercise 21 Sorting an array..................................................659.1.4. Multidimensional Arrays...................................................67

Exercise 22 Creating a multidimensional array.....................689.1.5. Declaring and using vectors..............................................71

Exercise 23 Creating a vector to hold exam results...............72Exercise 24 Create a vector of objects...................................75Exercise 25 Using the insert() member function and iterators

769.1.6. Declaring and using lists...................................................78

Exercise 26 Merging lists.......................................................79

10 More on Functions.................................................8210.1.1. Multiple arguments and default values...........................82

Exercise 27 Functions with multiple arguments and default values 82

Feb 2009 v OUCS

Page 6: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

10.1.2. Returning values from functions.....................................84Exercise 28 Returning a value from a function......................84Exercise 29 Classes and functions..........................................86

10.1.3. Passing Arrays to Functions............................................87Exercise 30 Passing Arrays to functions.................................87

10.1.4. Passing Two-dimensional Arrays to Functions................91Exercise 31 Multi-Dimensional Arrays and functions.............91

10.1.5. Overloading functions.....................................................94Exercise 32 Function Overloading..........................................94

10.1.6. Function Templates.........................................................97Exercise 33 Function Templates.............................................97

11 Pointers................................................................10111.1.1. Initialising pointers.......................................................101

Exercise 34 Using pointers...................................................10211.1.2. Pointer Arithmetic and Arrays.......................................103

Exercise 35 Pointers and Arrays...........................................104

12 Classes and Interfaces.........................................10812.1.1. Interfaces......................................................................108

Exercise 36 Creating an Interface........................................108

13 Appendix...............................................................11113.1.1. Arithmetical Operators..................................................11113.1.2. Assignment Operators...................................................11113.1.3. Assignment and Arithmetic examples...........................11213.1.4. Relational and Equality Operators................................11213.1.5. Logical Operators..........................................................11313.1.6. Escape Sequences.........................................................11413.1.7. Cast Operator................................................................11413.1.8. Formatted Output..........................................................11413.1.9. Header Files..................................................................11513.1.10. Scope...........................................................................11513.1.11. Enumerating constants...............................................11613.1.12. Constants.....................................................................11613.1.13. Vector member functions............................................11613.1.14. Global functions...........................................................11713.1.15. list member functions..................................................11713.1.16. cmath functions...........................................................11813.1.17. String class..................................................................119

OUCS vi Feb 2009

Page 7: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

13.1.18. ASCII Character set.....................................................122

Feb 2009 vii OUCS

Page 8: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

1 IntroductionWelcome to the C++ sessions 1-3.This booklet accompanies the course delivered by Oxford University Computing Services (OUCS), IT Learning Programme. Although the exercises are clearly explained so that you can work through them yourselves, you will find that it will help if you also attend the taught session where you can get advice from the teachers, demonstrators and even each other!If at any time you are not clear about any aspect of the course, please make sure you ask your teacher or demonstrator for some help. If you are away from the class, you can get help by email from your teacher or from [email protected].

1.1. What you should already knowThere is no prerequisite for this course. Having some programming knowledge will be helpful but the documentation is structured such that those new to programming will be able to follow the course at a pace suitable to them.The computer network in OUCS may differ slightly to what you are used to in your College or Department; if you are confused by the differences ask for help from the teacher or demonstrators.By the way, did we say that you can ask for help from the teachers or demonstrators !

1.2. What you will learnIn this session we will cover the following topics:Working with Dev-C++;Creating first programs;Fundamental data types, strings, casts;Classes and objects;Attributes and behaviours;Member functions;Constructors;Destructors;Header FilesInterfacesControl FlowArrays and VectorsFunctions

1.3. Where can I get a copy?

Feb 2009 1 OUCS

Page 9: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

You can download a copy of Dev-C++ from http://www.bloodshed.net/

OUCS 2 Feb 2009

Page 10: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

2 Things to understand

2.1. Compilers, new and oldNot all C++ compilers comply with the official ISO C++ standard which was published in 1998. For detailed information on which compilers support the standard see http://www.cuj.com/documents/s=8193/cuj0104sutter/.What does this mean? It means the code you write, compile and run on one machine may not compile on the next machine (even if it is using the same operating system) if you are using a different compiler. In this course you will be using Dev-C++ compiler. This is freely available to download from http://www.bloodshed.net/devcpp.html.Some older header files you may see with inherited C++ code are:#include <iostream.h> have a .h extension. The C++ standard for this header file is #include <iostream>. Your program may run correctly by adding a .h, but simply adding a .h suffix will not work for all included files.#include <string.h> has been replaced with #include <string>. The string.h header file does not include C++ strings, it includes C strings.#include <math.h> has been replaced with #include <math>. The lesson to be learnt here is that a lot of C++ code you come across will have been created on older compilers. Some of the header and other code will not be recognised and may cause compilation errors when compiled on a machine which is more compliant with the C++ standard.

2.2. The C++ Standard Template Library (STL)The C++ programs you write will consist of classes and functions. During this course you will program each piece that you need to form a C++ program. However, we will look at C++ Standard Template Library which holds a collection of existing classes and functions that you can use in the programs you will be creating.Some of the STL classes we will be looking at are:

The string class (actually part of the standard library) The vector container template The sort algorithm The list container template The find algorithm

Feb 2009 3 OUCS

Page 11: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

OUCS 4 Feb 2009

Page 12: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

3 Object Oriented Programming (OOP)3.1. Object Oriented programming Concepts

C++ is an object oriented programming (OOP) language. This means in the programs you create you will work with real world objects. Common objects are people, planes, cars, buildings, birds and many more. There are many other objects that you see and interact with each day. The objects you use in C++ will be created (instantiated) from the class code you write. Classes contain functions that implement operations and data that implements attributes.Real world object and class objects share two characteristics: They both have a state and behaviour . For example, cars have a state (speed, number of wheels, number of seats, colour) and behaviour (moving, stopped, braking, accelerating, slowing down, changing gear). Class objects are modelled after real-world objects so they too have state and behaviour . A software object maintains its state in one or more variables where data is stored. A variable is an item of data named by an identifier. A software object implements its behaviour with member functions. A member function is a subroutine and is always associated with an object. Languages like C are procedural and the programming tends to be action oriented. C programs are written using functions that contain the code to implement certain actions or tasks. In C++ we work with classes and objects . So, what is the relationship between a class and an object? To build a house you need a plan of the proposed layout. You can build many houses from the one plan. If you have a house class then it is possible to instantiate (create) many objects of the house class. Classes can also have relationships with other classes. There may be associations between the house class, a builder class, a surveyor class, a buyer class and others.In OOP it is possible to define classes in terms of other classes. For example, Jaguar X-Type, Mazda RX3, Bentley, Ford Focus are all kinds of car. In object-oriented terminology, Jaguar X-Type, Mazda RX3, Bentley, Ford Focus are all subclasses of the car class. Similarly, the car class is the superclass of Jaguar X-Type, Mazda RX3, Bentley, Ford Focus. Each subclass inherits the states (variables) and behaviours (functions) from the superclass. This means the subclass automatically contains the variables defined in their superclass. The subclass members Jaguar X-Type, Mazda RX3, Bentley, Ford Focus share the states: number of seats, colour etc of the superclass. Each subclass also inherits member functions from the superclass. Jaguar X-Type, Mazda RX3, Bentley, Ford Focus will share some behaviours of the superclass. Braking, accelerating and changing gear are possible examples.

Feb 2009 5 OUCS

Page 13: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

However, subclasses are not limited to the state and behaviours provided to them by their superclass. Subclasses can add variables and functions (sometimes called methods) to the ones they inherit from the superclass. It is common practice to define common behaviours in superclasses and fill in specific details with specialised subclasses.

OUCS 6 Feb 2009

Page 14: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

4 Installing Dev-C++What is Dev-C++? Dev-C++ is a freely available C++ compiler. One thing is for sure, we speak a different language from computers and there is no way a computer cannot understand the spoken or written language we use in our daily conversations. To make maters worse we do not understand the binary language that our computers use to perform complicated tasks. This suggests we have a communication problem.So what is a compiler and how can it help? The compiler is a tool that allows us to write instructions in some specially defined language (unfortunately not English, yet) in our case C++, which us humans can understand. This is called the source code (a high level language code). The compiler then converts this precise language (C++) into a concise language that the computer can understand called object code (a low level language code). This object code will most likely be used by other programs in the process of creating a working program.

4.1.1. Installing Dev-C++

Exercise 1 Installing Dev-C++ Install Dev-C++

Task 1Install Dev-C++

Step 1 Using Windows Explorer or My Computer navigate to the H:\ drive and double click on the program devcpp-4.9.9.2_setup.exe , see Figure 1.

Figure 1

Feb 2009 7 OUCS

Page 15: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2

Click OK when you see the installation window prompt shown in Figure 2.

Figure 2

Step 3

From the Installer Language window select English (or a language of your choice) then click OK . See Figure 3.

Figure 3

Step 4 Click the I Agree button when you get to the License Agreement window, see Figure 4.

Figure 4

OUCS 8 Feb 2009

Page 16: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 5 Click on Next when you see the Choose Components window, see Figure 5.

Figure 5

Step 6 Click the Install button at the Choose Install Location window. See Figure 6.

Figure 6

Feb 2009 9 OUCS

Page 17: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 7 Click on the Yes button at the prompt shown in Figure 7.

Figure 7

Step 8 To complete the installation click Finish , see Figure 8.

Figure 8

Step 9 At the Beta version Notice click OK , see Figure 9

Figure 9

OUCS 10 Feb 2009

Page 18: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 10 When you see the Dev-C++ first time configuration window (Figure 10) click the > Next button.

Figure 10

Step 11 Make sure Yes, I want to use this feature is selected then select the > Next button to select additional features, see Figure 11.

Figure 11

Feb 2009 11 OUCS

Page 19: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 12 To create the code completion cache click the > Next button, see Figure 12.

Figure 12

Step 13 Dev-C++ should now be successfully configured, see Figure 13. If you do NOT see this window, speak to the teacher or one of the demonstrators. Select OK .

Figure 13

OUCS 12 Feb 2009

Page 20: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 14 Close the Tip of the day window by clicking the Close button, see Figure 14.

Figure 14

Step 15 Dev-C++ installation has finished and you are now ready to write you first program. Instructions on how to do this are in Section 5.1.1

Figure 15

Feb 2009 13 OUCS

Page 21: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

5 Creating your first program5.1.1. Creating your first program in Dev-C++

Exercise 2 Creating a first program Open Dev-C++ Add a first program

Task 1Create your first program.

Step 1 If Dev-C++ is not already running, open

the program by double clicking on the icon in

the NAL window or select Start | All Programs | Bloodshed Dev-C++ | Dev-C++ .

Step 2 Select File | New | project . The dialog box shown in Figure 16 appears.

Figure 16

Select Console Application

Add a project the name of Welcome

Select the C++ Project radio button

Click OK

Save the project to the H:\ as Welcome.dev see Figure 17

OUCS 14 Feb 2009

Page 22: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Figure 17

Dev-C++ creates a basic template source code file you that you can build on. See Figure 18.

Figure 18

5.1.2. What does this first C++ program do?#include <cstdlib>This statement is a pre-processor directive to include the contents of the header file cstdlib in this program. This allows us to use functions for conversions of numbers to text, text to numbers, memory allocation and many other utility functions. You will be making use of these functions available in header file as the course progresses.

#include <iostream>Notifying the pre-processor to include in the program the contents of the header file iostream before compilation. This file must be

Feb 2009 15 OUCS

Page 23: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

included for any program that outputs data to the screen or inputs data from the keyboard

using namespace std;

"namespaces" are an advanced C++ feature. Dev-C++ adds the above statement and for now we should accept this in the program. Using the namespace std means we can use members of this namespace in our programs. The members we will be using throughout our programs are:cin - is the "standard input stream object" of the namespace std and we must include the header file <iostream> in order to use them (you will be using this in the next exercise). The cin object enables a program to input data from the keyboard or other device.cout - is the “standard output stream object” of the namespace std (you will be using this in the next exercise). The cout object enables a program to output data to the screen or other devices

endl - is a stream manipulator that writes a new line to output. endl stands for end of line and is pronounced “endell”.

int main(int argc, char *argv[]) - main() is part of every C++ program. The parenthesis () after main indicate that main is a program building block called a function . Inside the function parenthesis are arguments passed to the function. They are :

argc - is a count of the arguments supplied to the program of type int (integer). *argv[] is is an array of pointers to the strings which are the arguments.

In the programs we will be creating in this session we will not be using the arguments argc and *argv[] and the statement int main(int argc, char *argv[]); could be replaced with int main().

system("PAUSE"); statement is used to keep the command prompt in view when running command line programs with this compiler.

return EXIT_SUCCESS; tells the OS the program completed successfully. An alternative way of writing this statement is: return 0;

OUCS 16 Feb 2009

Page 24: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 3 Modify the program Prompt the user to enter a number Read in the number Output the number to screen

Task 1Modify the program

Step 1 Add the following statements immediately above the statement system(“PAUSE”);int anum = 0;

cout <<"Enter a number ";

cin >>anum;

cout <<"The number you entered is : " << anum << endl;

Step 2 Save the file as main.cpp

The statement int anum = 0; defines a variable (a memory location) called anum to store a number of type int to hold an integer (i.e. 1, 4, 27). The memory location is initialised with a value of 0. It is good practice to initialise variables at the same time you define them.cout <<"Enter a number "; cout is a name that belongs to the "namespace" std . The << is the "stream insertion operator". When the program executes, the value to the right of the operator (“Enter a number”) is inserted in the output stream and output to screen.cin >> anum; cin is the "input stream object" of the "namespace" std . >> is the "stream extraction operator" used to get the character from the keyboard.cout <<"The number you entered is : " << anum << endl; This statement concatenates the output by using multiple stream insertion operators. << endl is the stream manipulator that adds a new line.

Feb 2009 17 OUCS

Page 25: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2Compile the program

Step 1 Select Execute | Compile

If you have any errors in the code the line containing the error will be highlighted. Correct any errors and compile the program again. Repeat as necessary.

Click Close on the Compile Progress dialog box when there are no compilation errors

Task 3 Run the program

Step 1 Select Execute | Run

Enter a number at the command prompt, see Figure 19 and press Enter

Figure 19

The output is shown in Figure 20.

Figure 20

OUCS 18 Feb 2009

Page 26: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

5.1.3. Arithmetic Operators

Most computer programs perform arithmetic calculations. Table 1 summarises the C++ arithmetic operators. When working with integer division where both the numerator and denominator are integer the expression 15 / 6 evaluates to 2. To get the remainder after integer division you would use the modulus operator %. Note: the modulus operator can only be used with integer operands. To establish the complete result of the following integer division, 15/6 requires two operations.15 / 6 = 215 % 6 = 3The result being 2 remainder 3.

C++ Operation

C++ arithmetic operator

Algebraic expression

C++ expression

Addition + y + 6 y + 6Subtraction - a - b a - bMultiplication * c * d or cd c * dDivision / x/y or or x / y

Modulus % p mod q p % qTable 1

5.1.4. Other fundamental data types:

Table 2 shows how you would declare and initialise four other data types for use in programs.

Data type ExampleDouble double aDouble = 123.456;

Float float aFloat = 12.34;

Char char aChar = 'A';

Bool bool aBoolean = true;Table 2

5.1.5. Characters

Characters are normally stored in variables of type char, but can also be stored as integer data types. Characters are represented as single byte integers in the computer so it is possible to output a character as an integer or as a character.

Feb 2009 19 OUCS

Page 27: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

All characters have a numerical representation in the computer and the ASCII (American Standard Code for Information Interchange) character set shows each character and its decimal equivalent. See appendix 13.1.18.

Characters can be read in with the following statements:char aChar; declares a variable (aChar) of type char.cin >> aChar; this statement is used to read a character into the variable aChar.

Note: After entering a character the <ENTER>key must be pressed before the number is read by the program. To ensure the <ENTER> key press is ignored in the program add the statement: cin.ignore(); cin.ignore() is a function that reads and discards a character, in this case the <ENTER> key press.

The following four statements correctly declare a variable of type char, output a user prompt, then read a character and store it in the variable aChar. The enter key press is then ignored.char aChar;cout << "Enter the CHARACTER A: " ;cin >> aChar;cin.ignore();

Characters can also be read into a program and stored as integers. The statementbInt = cin.get(); uses the cin.get() function to read one character from the keyboard and store it in integer variable bInt. The integer variable can then be cast to a character, see section 5.1.7 Casts .

5.1.6. strings

Next to numbers, strings are the most commonly used data type in programming.A string is a sequence of characters such as “Oxford” or “St.Andrews”. In C++ strings are enclosed in quotes. The quotes are not part of the string, they identify the data type as a string.

Strings can be declared and initialised in this way: string name = “Oxford”; string firstName = “Ann”;

OUCS 20 Feb 2009

Page 28: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

To use the string type in your programs add the header file #include <string> at the top of your program. This allows the use of part of the C++ library of classes, the string class and its member functions.

The four statements below allow you to declare a string, read the string in and output to the screen

string name;

cout << "Enter your name ";

cin >> name;

cout <<"You say your name is: " <<name <<endl;

Note: When reading in a string with a space such as “Ann Black” only the first name is read into name. You could create a second string and get the user to enter Black but this is inconvenient. To handle this situation use the getline(cin, name); command instead of cin >> name;. This reads all key strokes into name until the <ENTER> key is pressed. The getline function (more on functions later) creates a string containing all of the characters from the input.

The string class has many useful functions you can use to manipulate strings. An example is the length() member function.

string myName = "Sebastion";

cout <<"The length of the string myName is "<< myName.length() <<endl;

This statement will output: - The length of the string myName is 9 .

See Appendix 13.1.17 for more information on the string class and member functions.

5.1.7. Casts

On occasions in your programs you may want to store a value in a variable of a different type. When there is a danger of a loss of information the compiler will issue a warning. If you try to store a double as an integer you can lose information in two ways.

the fractional part may be lost the magnitude of the number being stored is too big

It is not possible to store 34.78 *1030 as an integer because the number is larger than can be represented as an integer. However, you can store 123.0 as an integer.

Feb 2009 21 OUCS

Page 29: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

When you need to represent a value as a different type you can use the static_cast notation as shown here:

To change a double to an integer:

int anInt;

anInt = static_cast<int>(doubResult); where doubResult is a double.

Legacy code may use the following notation to cast different data types:

anInt = (int) (doubResult);

To change an integer to a character:

char aChar;

aChar = static_cast<char>(bInt); Where bInt is an integer.

OUCS 22 Feb 2009

Page 30: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 4 Create additional projects Examine how comments can be added to a program Examine the use of strings and fundamental data types using different data types using the cast operator using string class

Task 1Open the project CharNumString.dev on the H:\ and examine the program. Note how the string class has been used together with its member function length() .

Step 1 Examine the program CharNumString.cpp

The text at the top of the page starts with a (/*) and ends with (*/).

/*This program ……… data types.*/.

This is a block comment and is ignored when the program is compiled. The comment is over several lines and gives the reader information on how the program works.

Another way to write a comment on one line is by putting two forward slashes in front of the text:

//this comment is on one line

Comments written this way must be on one line only.

All comments are ignored when the program is compiled.

Examine the program and read all the comments. The comments explain step by step how the program works. It is good practice to comment your program.

Further exercises can be completed by copying parts of this code and adding additional functionality as required.

Task 2Create another project, call it Even . Write a program that will read in two numbers of type double and two numbers of type integer . The program should output the sum, the product and the difference of the double numbers. Also output the quotient and the fractional part of the two integers.

Feb 2009 23 OUCS

Page 31: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 3Modify your program in Task 2 to read in two characters. Enter the characters “a” and “Z”. Output the two characters with the character case changed. i.e. “a” becomes “A” and “Z” becomes “z”. You will need to look at the Appendix 13.1.18 to establish the ASCII integer values of each character.

Task 4Create another project called Address . Write a program that can be used to collect user data. Output this data to screen as shown in Figure 21.

Figure 21

OUCS 24 Feb 2009

Page 32: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 5Create another project call it CalcArea.dev .Write a program to calculate the area of a circle for different radius.Extend the program to calculate the circumference.Extend it again to read in the height of a cylinder and calculate its volume.∏ = 3.141592a = ∏r2, c= 2∏r, v= ah

Task 6 Create another project call it CtoF.The program will prompt the user to enter a temperature in centigrade. The program will calculate the equivalent temperature in Fahrenheit and output this to screen. The formula is fahrenheit = 1.8 * celsius + 32;

Feb 2009 25 OUCS

Page 33: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 7Create a project called SearchString.dev .The program will display a string of text to the user. The user will then be prompted to select a word from the sentence then input a replacement word. See section 13.1.17.The string before and after the update should be displayed, see Figure 22.

Figure 22

OUCS 26 Feb 2009

Page 34: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

6 Introduction to FunctionsFunctions are used to encapsulate a set of operations and return information to the main program or calling routine. Encapsulation is data, information or detail hiding. Once a function is written, the detail of how it works is not important. It is only necessary to understand what data input the function needs (its parameters) and what output is produced. The use of functions provides several benefits. It makes programs significantly easier to understand and maintain. The main program function can consist of a series of function calls rather than hundreds of lines of code. A second benefit is that well written functions can be reused in multiple programs. A function is declared with a prototype early in the program. A function prototype consists of the return type , a function name and a parameter list indicating the data the function will receive. The function prototype is also called the function declaration .The function definition consists of the prototype and a function body, which is a block of code enclosed in parenthesis. Using a prototype is a way of telling the compiler the data types of any return value and of any parameters being passed, to enable error checking to be done. The definition creates the actual function in memory. Arguments can be passed to functions in two ways. pass-by-value is where a copy of the argument value in the main program is made and then passed to the function. The copy in the function only exists in memory as long as the function is active. When the code within function has been run the memory is released and the value held there lost. Changes to the copy of the variable in the function do not affect the original variables value. Arguments can also be passed-by-reference . When arguments are passed in this way any changes made to the arguments in the function are reflected by corresponding changes to that data variable in the calling part of the program. Pass-by-reference is good for performance reasons because it can eliminate the pass-by-value overhead of copying large amounts of data. In later sections we will examine how pointers can be used to pass-by-reference.

6.1.1. Creating a functionThe format of a function prototype is:return_data_type AnyFunctionName (argument_list) The statement void FtoCent(int temp); has no return data type (void), it’s name is FtoCent and it accepts an argument called temp of type int (integer). It is not strictly necessary to give the argument a name (temp) in the prototype. However, the argument type must be specified. The

Feb 2009 27 OUCS

Page 35: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

statement void FtoCent(int); is an alternative prototype and will compile satisfactorily.The following exercise is an introduction to functions. You will learn a lot more about functions in later exercises.

OUCS 28 Feb 2009

Page 36: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 5 Examining a function Open project CharNumStringFunc.dev from the H:\ Examine the structure of the program with a function prototype

above main() and the function definitions beneath main() Identify the static keyword

Task 1Open the project CharNumStringFunc. dev on the H:\ drive.

Step 1 Compile the program, sorting any compilation errors.

Run the program entering the data as requested. The output should be the same as Figure 23.

Figure 23

Step 2 Examine the following statements. Only the important parts of the program are explained, the rest has been covered in previous exercises.

All functions must be declared prior to use and there are four prototypes in this program. Creating prototypes allows the compiler to perform type checking on the arguments to ensure the input data is the correct type before processing it.

void readChar(); function prototype. The function is passed no value and returns no value. Note the use of void .

Feb 2009 29 OUCS

Page 37: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

void passReadChar(int); function prototype. This function receives an argument of type int (integer) and returns no values.

int passStringRetInt(); function prototype. This function returns an integer, int. No values are received by the function ().

void readDouble(); function prototype. No values are passed to the function and it returns no value (void).

Calling functions:readChar(); This is a function call to the readChar() function. Notice no parameters are passed. The function must therefore contain the code to read in and output the user input.

passReadChar(aInt); This statement calls the function passReadChar() and passes a character into the function. The character argument is passed as an integer.

cout <<passStringRetInt()<<endl<<endl;

In this statement passStringRetInt() is a function call and the integer returned from this call represents the number of characters there are in the name input from within the function. Look at the prototype for this function. You can see the function returns an integer. When this statement is output the function name is effectively replaced by the return value, the number of characters in the name input.

readDouble(); This function call does not pass a value to the function and nothing is returned. The function reads a value and outputs the square of the value read in. Note how this function is called three times but the code is contained within a function and written once.

OUCS 30 Feb 2009

Page 38: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Function Definitions:void readChar()

{ }

This is the function definition for readChar(). The code within the braces is used to read in a character and output the value to screen.

void passReadChar(int number)

{ }

In this function an integer is passed to the function. As characters are represented as single byte integers it is possible to change the integer read in to a char.

int passStringRetInt()

{ }

The user enters a string in the function. The number of characters in the string is established using string class member function length() . This is returned to the calling statement.

void readDouble()

{

static int aNum = 1;

aNum +=1;

}

Note here the use of the keyword static . This has defined the memory location aNum as static and this cannot change. Memory is normally allocated to function variables as the functions are called. When the function call is complete the memory allocated is released and all data in the function variables lost. Using the keyword static means memory is allocated from a different part of memory and value in the variable is maintained throughout the life of the program. The statement aNum +=1; increments the static variable by 1 each time the function is called using the assignment operator += . In this example 1 is being added to the variable aNum .

Feb 2009 31 OUCS

Page 39: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2Remove the key word static from the declaration static int aNum = 1; This is in void readDouble() function. Compile and run the program and see how the program responds.

OUCS 32 Feb 2009

Page 40: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 6 Writing functions Open the project Even you created in Section 4, Exercise 4 Create two functions Move calculations to functions Return a value from the function

Task 1Open the project Even.dev you created in Section 4, Exercise 4 and change the structure of the program to make use of functions.

Step 1 Read two integers in to main() and pass them to a function. The prototype is void intCalcs(int, int);

intCalcs() function should calculate and display the result of the division and modulus of the two variables passed, see Figure 24.

Read in two doubles to variables in main() . Pass the two doubles and the value of one integer to the second function, the prototype is int Calcs(double, double, int);

Within function Calcs() write statements to produce the output as shown in Figure 24. Most of the code already exists within main() . Return the result of the multiplication of one double and an integer, cast this value as an integer. Display the returned value within main(), as shown in the second last line in Figure 24.

Figure 24

Feb 2009 33 OUCS

Page 41: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2 Create a separate function to change the character case of two characters. The characters should be passed from main() to the function and the results of the changes displayed from within the function. Task 3 Create a new project call it ChurchHeight.dev. Write a program that will calculate the height of a building given the following information.You are 270 metres away from a church. The angle from your feet to the top of the church is 16 degrees, see Figure 25 and Figure 26.The height of the building can be calculated using the formula: tan(angle) = length of opposite side/ length of the adjacent side.radians = degrees*∏/180.The program should contain at least two functions to calculate the height of the building. You will need to convert the angle to radians before using the cmath function tan(x). See Appendix 13.1.16 for more information on cmath functions.Remember to include the header file <cmath> in your program.

Figure 25

Figure 26

OUCS 34 Feb 2009

Page 42: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 4 Create a new project call it Metres.dev .Write a function named FItoMeters which takes two double parameters, a number of feet and a number of inches and returns a double number of equivalent meters. Assume there are 2.54 centimeters (0.0254 meters) in one inch.

Task 5 Create a new project call it Seconds.dev .Two identical experiments have been conducted and the time difference between the two (in seconds) is critical. Write a function (HMSeconds) that will be called repeatedly and will take three integer parameters. A number of hours, number of minutes, and number of seconds. The total in seconds will be returned to main() and used in further calculations to analyse experimental results.

Feb 2009 35 OUCS

Page 43: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

6.1.2. Functions and Pass by Reference

In the previous section when working with functions all arguments passed to the functions were copies of variable values from main(). The arguments were passed by their value .Pass by Value is the default argument passing mechanism for C++. When a function is passed an argument it gets a copy of the value from the calling function (main() in previous examples). This copy value remains in scope until the function call has completed when the copy in the function is destroyed. Therefore a function that takes value-arguments cannot change the variable passed from main() because any changes only apply to local copies in the function, not the actual caller's variables.Passing variables to functions by reference is very useful when we need to change or update variable(s) via a function. Pass by reference involves passing an address and not a copy of the data to the function. This is usually more efficient than passing by value because there is no requirement to copy large parts of memory. However, this argument passing mechanism enables a function to modify any function arguments even if it's not supposed to. To avoid this, declare all read-only parameters as const and pass them by reference.The format of a function prototype when using call by reference is:return-data-type function-name (reference parameter). To indicate a reference parameter, an ampersand (&) is written in the function prototype and header after the parameter type name The statement void squared(int &); has no return data type (void), it’s name is squared and it accepts a reference parameter (&) of type int (integer).

The function definition would be: squared(int & inVal)

{

inVal * = inVal;

}

The function call would be:squared(aValue);

OUCS 36 Feb 2009

Page 44: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 7 Pass arguments by reference Examine how parameters can be passed by reference Create functions using parameters passed by reference

Task 1Open the project FunctionRef.dev on the H:\ drive.

Step 1 Compile and run the program. The output should be the same as shown in Figure 27.

Figure 27 Examine the function prototype:

void squared(int &);

This shows the function squared accepts a reference parameter of type int. The reference parameter is the memory address of the argument passed to the function.

The function uses this address to both get and set the value stored in variable a , (21) in main(). A reference to this address is passed to the function with the function call squared(a);

Step 2 Examine the function void squared(int &x)

x refers to the address of (a) in main, that holds the number 21 .

When parameters are marked as reference parameters, the memory address of each argument is passed to the function. The function will use these addresses to both get and set values. The values changed are the variables stored where the function is called, main() in this example.

Feb 2009 37 OUCS

Page 45: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2 Create another project call it FuncRefMarks.dev. Read in the name of a student and three exam marks.The marking has been too severe in the three exams and all students are to receive an additional 5 marks. The student name has been entered incorrectly and needs to be changed. Prompt the user to enter the change in student name and value that each result will be increased by. Making just one function call modify the exam results and the student name. All the variables should be stored in the main() function. The output should be similar to that shown in Figure 28.

Figure 28

OUCS 38 Feb 2009

Page 46: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 3 Open the file FuncConstRef.dev and examine the program. Compile the program sorting any errors. Arguments are being passed by reference but incorrectly, sort these errors. There are also some problems with the program logic. When the program is compiled and run the output should be as shown in Figure 29.

Figure 29

Feb 2009 39 OUCS

Page 47: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

7 Classes and Objects

In the previous section we have been working with simple programs that display messages to the user, store data input as different data types, manipulate the data in some way and output the results to screen. We now look at objects and classes. In the real world there are objects everywhere, students, staff, cars, birds, houses and many more. All objects have attributes, these are similar to the variables created in previous tasks. Some attributes of a student may be height, weight, race, course of study etc. All objects exhibit behaviours or operations, cars accelerate and decelerate, students matriculate, enrol on courses and leave university.Now, what is the relationship between a class and an object? A good analogy would be, from a drawing for a house it would be possible to build many houses, and from a class it would be possible to build many objects. If we had a student class we could create many objects from the student class to represent the many students enrolling. Each of these objects would be uniquely identified. They would share common attributes and exhibit common behaviours. If we wanted an object to perform some task we would call the appropriate member function allowing an operation to take place changing the behaviour of that object. Member functions are different from the functions you have created so far. Member functions are always associated with objects and are called or invoked with a dot notation, object.memberfunctionname(). An example is student1.getName() . The object is student1 and the member function is getName() .Member functions contain the detail of how the technical aspects of some operation will be processed. When member functions are invoked these technical issues are hidden from the end user. When the member function is asked to do some operation a message is sent (a member-function call) telling the member function of that object to perform the operation detailed in the function.Functions are not completely new, we have had a brief introduction and you have already created some of your own. Note also that main() is a function and is called automatically when you run your programs. However, it is not a member function as there is no object associated with it.

OUCS 40 Feb 2009

Page 48: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

7.1.1. Creating your first class

Exercise 8 Creating a class Create a class Create an object of the class

Task 1Create a new project call it Student . Name the new source file StudentUG.cpp . Open the text file called StudentUG.txt from the H:\ drive. Copy the C++ program. Replace the default C++ template file (StudentUG.cpp) with the file copied from StudentUG.txt . The program should look like Figure 30. Compile and run the program.

Figure 30

Before you can create the object myName it is necessary to define the class from which the object will be created. The class definition is shown below.

class StudentUG { /*start of class definition*/

public: /*public is access specifier, it means the function displayName()

(a member function) is open to the public. It can be called by other functions in the class and functions of other classes*/

void displayName() /*start of member function */{

Feb 2009 41 OUCS

Page 49: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

cout <<"My name is Larry Martin" <<endl;} /*end of member function */

}; /*end of class definition. *//*Note: a semicolon is required at the end of the class definition*/Within main() the statement StudentUG myName; creates the object myName of class StudentUG.

The statement myName.displayName(); is used to call the member function displayName() of object myName .

As we have seen previously the function main() is called automatically when our programs are executed. However, member functions (displayname() is one, we could have many) must be called in this way, objectName.functionName() .

The member function displayName() is preceded by the word void. All functions can return values, this one does not. The word void preceding the function name indicates nothing is being returned. If this function returned an integer the definition would be int displayName() .

When you use functions it is common to pass data (called parameters) to the function. The function then manipulates the data before displaying an output and/or returning a value.

To pass a parameter to the function in the studentUG class the calling statement in main() would be:myName.displayName(name); where name is a string (a series of characters) that contains a value read in from the keyboard.

In order for the function displayName() to recognise the parameter being passed the function declaration is changed to include the parameter (name) and type (string) as shown in Figure 31.

Figure 31

The statement cout <<"Hello " << name << endl; provides the output.

OUCS 42 Feb 2009

Page 50: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

7.1.2. Member functions and Passing parameters

Exercise 9 Passing parameters Function calls with parameters

Task 1Modify the program you created in the previous exercise StudentUG.cpp to read in a student name. The name should be passed to a member function. The parameter should be output from within the function to welcome the user to C++ programming. The output should be similar to Figure 32.

Figure 32

Task 2 Modify the program in the above task to read in two more names. Each name will be for a different student and you will need to create additional objects (instances) of the class.

7.1.3. Data MembersIn all the programs written so far, the variables have been declared inside the main() function. Variables declared inside a function are local to that function and cannot be accessed from outside that function. You have created a student class and it would be reasonable to assume that a student would be following a particular course. So courseName might be one of several attributes of a Student object. Attributes are represented as variables in a class definition . These variables are called data members and must be declared inside a class definition. When you create an object of a Student class each object has a unique memory location for its data members.Figure 33 shows data member studName declared in the class definition. The access specifier private means that only member

Feb 2009 43 OUCS

Page 51: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

functions of the class in which the attribute was declared can use this data member.

Figure 33

When data members are declared as private the data is hidden. This is called encapsulation and means the attributes of the object are hidden and can only be accessed via member functions.As there is no direct way to change a data member you will also need to create a member function to set the data member to a value and create a second member function to output the value held there.Data members can also be declared public. A data member that is declared public can be accessed from any (non-member) function.A protected data member can only be accessed by member functions of its own class and by member functions of classes derived from this class. We will learn more about derived classes and inheritance later.

Exercise 10Using data members Setting a data member Getting a data member

Task 1Create a new project call it StudentGetSet.dev . Create a new source file call it StudentCourse.cpp . Open the text file called GetSet.txt from the H:\ drive. Copy the C++ program. Replace the default C++ template file (StudentCourse.cpp) with the file copied from GetSet.txt . Compile and run the program, it should look like Figure 34. You may have to sort some compilation errors.

Figure 34

OUCS 44 Feb 2009

Page 52: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2Examine the member function returnName() shown in Figure 35. This function produces the output but what does getName() do?

Figure 35

Task 3Modify the StudentCourse source file to enable the user to add a student name, enrolment date and number of years of course. Once entered this data should be output to screen. You will need to create additional data members and member functions to achieve this.The output should be similar to Figure 36.

Figure 36

Feb 2009 45 OUCS

Page 53: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 11More Objects Creating a second object

Task 1So far you have created one StudentCourse object. It is about time we had a second student on the course. Create a second object of the class StudentCourse . You will need to add the second statement shown in Figure 37 to add the new object yourName . Call the member functions passing parameters as necessary.

Figure 37

7.1.4. ConstructorsWhen you create objects from the StudentCourse class it is necessary to give initial values to all the data members. If we were entering data for five people and they were all following the same course of study it would make sense to initialise the courseName data member (it is possible to initialise some or all of the data members) when each object is created. A constructor is a special kind of function that must have the same name as the class. Constructors are normally defined as public and never have a return type. They can be used to automatically initialise data members. In previous programs you have written, a default constructor has been provided by the compiler. However, it is not possible to pass parameters to a default constructor function, so the data members in the programs created so far have not been automatically initialised. To initialise these data members you created member functions that assigned values to data members. Although a default constructor is provided at compilation time it is a good idea to create your own so that the data members can be initialised.It is worth noting here that functions (constructors are functions) can be overloaded. This means it is possible to have more than one function with the same name. Note that overloaded functions (functions with the same name) must have different types of, or number of arguments.Constructors (functions) can also be overloaded with more than one function with the same name but different types or number of parameters. Fortunately for us the compiler automatically calls the

OUCS 46 Feb 2009

Page 54: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

correct function whose parameters match the arguments used in the function call. There is more information on function overloading in section 10.1.5.

Exercise 12Using constructors Create a new file using constructors Add a third constructor

Task 1Create a new project call it Constructor . Create a new source file call it Constructor.cpp . Open the text file called constructor.txt from the H:\ drive. Copy the C++ program. Replace the default C++ template file (Constructor.cpp) with the file copied from constructor.txt . Compile and run the program, it should look like Figure 38. You may have to sort some compilation errors.

Figure 38

Task 2In the constructor shown in Figure 39 what does the statement setCourseName(name); do?

Figure 39

Feb 2009 47 OUCS

Page 55: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 3Create a third constructor that will take arguments of years and enrolDate . Add a third object, call it student3. Write a statement that will output the results of a call to this additional constructor.

Task 4 Each student has an ID number and a supervisor . Modify the program to allow student ID’s and the names of supervisors to be added to each object created. Create member functions to allow the user to add or modify both the ID and supervisor names . Create member functions to output these details to screen.

7.1.5. DestructorsBoth constructors and destructors are special class methods. We have seen how a constructor is called whenever an object is defined. A destructor is a method that has the class name prefixed by a tilde, ~. Destructors cannot return values and therefore have no return type specified. Unlike constructors, destructors have no arguments and thus cannot be overloaded. Overloading a function is using the same name for more than one function provided the functions have different parameter, see section 10.1.5. An object's destructor is called whenever an object goes out of scope. The purpose of the destructor is to clean up and free any dynamically allocated memory that the object was using and release other system resources. In the examples used so far no destructor has been provided for any class created. In these programs it has been unnecessary. If the programmer does not explicitly provide a destructor the compiler will

OUCS 48 Feb 2009

Page 56: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

create an empty destructor in the same way that an empty constructor is created if one is not explicitly created. When classes are created, any objects instantiated from them that contain dynamically allocated memory will need destructor methods (functions) added to implicitly free any dynamically allocated memory when the object goes out of scope.In the class example shown below the destructor function is ~ Staff ().

class Staff {

private:    int staffid;    double staffsal;

public:  

Staff (int staffid = 0, double sal = 0.0); /*constructor*/

 ~ Staff() {}; /* destructor*/

  

int getID()

{return staffid;

}

void setID(int id)

{staffid = id;

}

double getSal()

{return staffsal;

}

void setSal(double sal)

{staffsal = sal;

}

}; /*end of class*/

Feb 2009 49 OUCS

Page 57: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

7.1.6. Separate Class Files for ReusabilityThe programs you have created so far consist of one .cpp source code file that contains a class definition and a main() function. C++ is an object-oriented programming language and one of the aims is to create classes that are reusable. It is not possible to reuse the source code from the programs you have created so far. This is because each program contains a main() function. As things are, if you include an existing class file in a new program you will also be including a main() function. As there can only be one main() function, compiling this program will cause compilation errors.The way to reuse the class information in the source code file is to extract the class information and put it in a header file that has an .h extension.To get a new program to include the header file use the pre-processor directive #include .

Exercise 13Using header files Open an existing project Create a header file Use the pre-processor directive

Task 1Open an existing project. Create a header file and include reference to this in the source code file. When main() is called the class definition in the header file is used to create objects of the

Step 1 Open project Header.dev on the H:\

Add a new Source file to the project, File | New | Source File

Save and name the file OxStudents.h in the same folder as Header.dev .

OUCS 50 Feb 2009

Page 58: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

class defined in the header file.

Step 2 Cut the class definition code from Header.cpp file and paste it into the OxStudents.h file.

As you will be using input and output in the class header file you need to include the iostream library. Add #include <iostream> and using namespace std; to the top of the header file. Step 3

Compile the program

You should get a compilation error at line OxStudents myName; This is because main() does not know about the header file containing the class information.

Step 4 Add the statement #include "OxStudents.h" beneath the other #include directives in Header.cpp file.

Compile and run the program

The statement #include "OxStudents.h" instructs the C++ pre-processor to replace the directive with a copy of the contents of OxStudents.h before the program is compiled.With the OxStudents class in a header file it is now possible to include and reuse that class in any program by just adding the appropriate header file to main(). Note: User defined header files are normally kept in the same directory as the source code files.

Feb 2009 51 OUCS

Page 59: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2Create another project call it Country . Modify the main() source code to use the class in the header file #include "OxStudents.h" . Note: the Country project will have to be created in the same folder as Oxstudents.h

The user should enter a name and a country which should be output to screen, see Figure 40.

Figure 40

Task 3 Open the project Constructor.dev you created in Exercise 12. Create a new header file that includes the class definition, save this as constructor.h . To use the class from within main() add #include "constructor.h" at the top of the program where the other header files are included.Test the program.

OUCS 52 Feb 2009

Page 60: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 4 Create a new project call it Employees.dev .

Open the file Employees.txt on the H:\

Replace the default file in the project with Employees.txt .

Create a header file, call it employee.h .

Add two constructors, one default and another to accept the parameters being passed from main() .

Create member functions to:

set the salary modify the salary return the full name return the salary

Modify the main program to call the member functions.

The completed program should provide an output similar to Figure 41.

Figure 41

Feb 2009 53 OUCS

Page 61: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

8 Basic Control FlowThe programs you have created so far are limited in they run through a sequence of instructions once and then stop. Most computer programs will make decisions and carry out different actions determined by the user input. C++ has three kinds of control structures:

Sequence statement - the computer executes the statements one after another. All the programs you have written so far use sequence statements.Selection statements - if, if…else, switch.

The if selection statement selects an action if a condition is true or skips the action if false. The if...else selection statement selects an action if a condition is true or performs a different action if the condition is false.The switch multiple selection statement can be used to perform many different actions based on a character or integer value.

Repetition statements - while, for, do…while.The while and the for statements perform actions within their bodies zero or more times depending. If the loop condition test is initially false no actions will occur. The do…while statement will perform the actions in the body at least once.

8.1.1. Selection - if…else statementThe if selection structure is used to choose among alternative courses of action. The structure of the statement is: if (mark >= 50)

cout << "Passed";

else

cout << "Failed";

If the condition (mark >=50) is true the statement following it is executed cout << "Passed";

OUCS 54 Feb 2009

Page 62: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

If the condition is false the statement is ignored and control is passed to the else part of the selection, and statement following else is then executed cout << "Failed"; if…else selection statements can also be nested within other if…else selection statements.

Exercise 14if …else selection Open project If from the H:\ Examine how the if…else double selection statement works Modify the program

Task 1Open project If.dev on the H:\ drive. There is one .cpp file and one .h header file.

Step 1 Compile the program, sorting any compilation errors.

Run the program. The output should be the same as Figure 42.

Figure 42

Feb 2009 55 OUCS

Page 63: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Examine the void getGrades() member function in the StudentMarksInterface.h file.

The if single selection statement performs only one action when the condition tested (Exam1 >= 90) is true .

if(Exam1 >= 90) cout<< "the Exam1 grade is 'A'" <<endl;

The if selection statement returns true only when Exam1 is greater than or equal to 90 . The output is "the Exam1 grade is 'A'". There is no mechanism for testing for other scores with the single if selection statement and the program will continue with the next statement in the program.

Note: >= is a relational operator (greater than or equal to). For more information on relational operators see Appendix 13.1.4 Relational and Equality Operators.

To test for, and provide actions for two distinct conditions we can use the if…else selection statement.

It is necessary to specify an action when a condition is true (Exam1>=90 ) and an alternate action when the condition is false .

if (Exam1 >= 90) cout<< "the Exam1 grade is 'A'" <<endl;else cout<< "the Exam1 grade is 'B'" <<endl;

Although this is closer to meeting the requirements of the program it still needs to be improved.

By having nested if…else statements and using appropriate relational operators >= (see Figure 43) it is possible to test for multiple test scores.

Figure 43The appropriate grade is selected and user prompted of the result from within getGrades() member function.

OUCS 56 Feb 2009

Page 64: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2A second student has just joined the class. Modify your program so the user is prompted to add details for a second student and their results for the four exams. Modify the code so the user is prompted to add a Course Name .Output the results to screen. They should look similar to Figure44.

Figure 44

8.1.2. Selection - switch multiple selection statementThe switch multiple selection statement can be used to perform many different actions based only on a single integer value. Note however, the switch statement can only be applied in narrow circumstances. The tests must be constants and be integers. Let’s compare the two statements:

OK – Test is 1, a constant and an integer NOT OK – Test is not constant integer

Feb 2009 57 OUCS

Page 65: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 15switch selection Open project IfSwitch from the H:\ Examine how the switch double selection statement works Modify the program

Task 1Open project IfSwitch.dev on the H:\ drive. There are two files, one .cpp files and one .h header file.

Compile the program, sorting any compilation errors.

Run the program. The output should be the same as Figure 45.

Figure 45

OUCS 58 Feb 2009

Page 66: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2To see how the switch statement gets its parameters and to understand how characters can be used in a switch statement.

Step 1 Examine the void getGrades() member function in the StudentMarksInterface.h file, see Figure 46.

The use of the if statement was explained in the last exercise. The statement countGrades (‘A’) is new. It is calling the function countGrades and passing a character parameter ‘A’ as the student achieved >= 90 marks.

Other grades assigned and passed to the function are B (79-85), C (50-74) and F <=49.

Figure 46

Feb 2009 59 OUCS

Page 67: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Exam the code in countGrades member function. See Figure 47

Figure 47A character parameter is passed to the function.

All characters typed at the keyboard have a numerical representation in the computer and are stored as 1-byte integers. It is therefore possible to treat a character both as a character and as an integer.

As the character input at the keyboard can be represented as an integer it meets the criteria for use with the switch statement.

The switch statement consists of a series of case labels and a default case statement. In Figure 47 these are used to increment the different counters (aCount…fCount) depending on the value of parameter passed. If there is no match between the letter (the controlling expression) and the case labels the default case statement executes.

OUCS 60 Feb 2009

Page 68: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 3Exam how the count of grades is output.

Step 1 Examine the member function outPutGrades() shown in Figure 48

Figure 48This member function outputs the object member variables aCount...fCount. The statement student1.outPutGrades(); in main() is used to call the member function and output the total of each grade achieved by the object student1 .

Task 4 Create a new project call it ElectronicsOutlet.dev . You sell the following four products at the unit price shown. Product 1:Astable multivibrators @£15.45Product 2:Integrated-Circuit Timers @ £21.78.Product 3:ECL @£15.78.Product 4:BiCMOS digital circuits @£34.99.

Step 1 Write a program that reads a product ID (Product 1-4) and the quantity required.

A switch statement should be used to determine the product sold.

Items that are sold in quantities >99 units are reduced in price by 10% before tax is applied.

The output should show the cost per item, the VAT element and the total cost including VAT at 17.5% as shown in Figure 49.

Figure 49Note : Use a class file (header file). Create a default constructor to initialise all data members. Initialise the product ID, the Unit Cost and the product name in the switch statement. To do this you will need to overload the default constructor.

Feb 2009 61 OUCS

Page 69: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

8.1.3. Repetition – while, do…while and for loopsThe while statement is commonly used to carry out repeated steps, perhaps reading in values before doing a calculation on values read in. The format of the code is while (condition)

statementThis can be read as, while the condition is true continue to do the statements until the condition is false.

Exercise 16while loop Open project While project from the H:\ Examine how the while repetition statement works Modify the program

Task 1Open project While.dev on the H:\ drive. There is one .cpp file and one .h header file.

Step 1 Compile the program, sorting any compilation errors.

Run the program. The output should be the same as Figure 50.

Figure 50

OUCS 62 Feb 2009

Page 70: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Open the while.h file and examine the member function getStudentDetails().

The condition tested in this loop is the counter value. The statement while (counter <= 4) will only be true while the counter is less than or equal to 4. All the statements within the braces {} will be executed when the condition is true.

In this example, to make the condition false and terminate the loop, the counter value has to be incremented (it could be decremented depending on design).

The statement counter ++; achieves this, incrementing counter by 1. For more detail on incrementing variables see Appendix 13.1.1.

Note: It is easy to forget that the counter must be incremented or decremented (depending on how you designed the program). If you fail to change the counter value you will create an infinite loop where the statements inside the while loop will run forever.

Task 2Modify the program in the task above to read in the results of tests for two students. Each student has taken 4 tests. Output the total, average, highest and lowest scores for each student. Note: you will need to use a method of selection to establish the highest and lowest marks inside the while loop.

Feb 2009 63 OUCS

Page 71: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 3 Create a new project call it BMI.dev .The program should calculate the body mass index (BMI) of a person where their height is in feet and inches and their weight is in stones and pounds. 1 foot =12 inches, 1 inch = 25.4 mm, 1 stone = 14 pounds,1kg = 2.2 pounds.

BMI = weight(kg)/height(m)2

Offer some medical advice to the user using these criteria:BMI <25 = Good 25-29 = OK >29 = Overweight

Figure 51 shows the output from the BMI calculator.

Figure 51 BMI Calculator

OUCS 64 Feb 2009

Page 72: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 4 Create a new project call it avgTemp.dev.

Seven temperature readings are taken at each of three locations in Oxfordshire and stored.

Stored in class objects for each location are the details of the location: The nearest town and a six figure grid reference.

Create a temperature class to accept the temperature readings and other details for each location.

Calculate the mean temperature at each location and output this to screen. The output should be similar to that shown in Figure 52.

Figure 52

Task 5 Using the output shown in Figure 53 write a program that will output this display. Create a class file that can be used to display this detail. The program does not have to be functional other than to display this screen and verify the account and PIN numbers.

Figure 53

Feb 2009 65 OUCS

Page 73: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 17for loop Modify the program using the for loop

Task 1Modify the program in Exercise 14 Task 2 to use the for loop. You will need to modify the code in student.h .The code you need to add is shown in Figure 54.Note: The for loop is a special kind of while loop.

The format of the for loop is:

for (i = start; i <= end; i++)

{

Statements;

}

In the above piece of code it is assumed i is declared as a variable in the declarations section within the program.

Figure 54

Figure 54 shows the code required to read in four exam marks.

Note: The integer i used to control the loop and has been declared within the brackets of the for loop (int i = 0;). This means that i only exists within the loop. When the loop ends, i ceases to exist. This is called the scope of the identifier. See appendix Scope 13.1.10 for more information.

OUCS 66 Feb 2009

Page 74: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2 Create a new project call it Books.dev .The program should create three instances of a class called Books . Create each of the objects inside a for loop . Create member functions to add a Title, Author and date of publication.Output the details of the three books to screen.

Feb 2009 67 OUCS

Page 75: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 18do…while loop Understand the difference in while and do…while loops

Task 1Open the DoWhile.dev project on the H:\ drive and establish how the do…while loop can effect a program written to verify user input.

Step 1 Open DoWhile.dev project on the H:\ drive

Run the program entering the numbers 19, -19, 19, -19 when prompted

The output of the program is shown in Figure 55.

Figure 55 Establish why when using the do…while loop for repetition a negative value (-19 as shown in Figure 55) is established as being greater than zero.

Hint: Look at where in the block the condition is tested.

Task 2Create a new project call it Factorial.dev . Using different repetition statements write a program to calculate and display the factorial of a value entered by the user. See Figure 56.The factorial of '6' is 1*2*3*4*5*6 = 720.

Figure 56

OUCS 68 Feb 2009

Page 76: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

9 Arrays, vectors and listsArrays, vectors and lists are all types of data structures. Data structures are areas of memory where collections of the same data type are held. The main difference between arrays, vectors and lists is that arrays stay the same size throughout the program execution whereas vectors and lists can grow automatically to any size. Arrays consist of a series of elements (variables) all of the same type placed consecutively in memory. Each of the elements can be individually referenced by adding an index to a unique name. The advantage of using arrays compared to using discrete variables (the way we have stored values so far) is it is possible to store any number of values of the same type in an array without having to declare many different variables each with a different identifier. With arrays it is possible to store 100 student exam marks, or 100 student names with one unique identifier.

Vectors and lists are container classes, part of the Standard Template Library (STL). This is a general-purpose C++ library of algorithms and data structures that we can use in our programs. While some aspects of the library are very complex, it can often be applied in a very straightforward way that allows reuse of sophisticated data structures and algorithms.As with an array, vector and list can hold objects of various types. However, unlike arrays, vectors and lists can resize, shrink and grow as elements are added or removed. The standard library provides access via iterators, or subscripting. Iterators are classes that are abstractions of pointers (more on pointers later). They provide access to container classes using pointer-like syntax and have other useful methods as well. The use of vectors, lists and iterators is preferred to arrays and pointers. By using containers common problems involving accessing past the bounds of an array are avoided. Additionally, the C++ standard library includes generic algorithms (an algorithm is a set of instructions on how to perform a task) that can be applied to vectors lists and other container classes.

9.1.1. Declaring and using arraysArrays are declared indicating the type and number of elements in the following way:type arrayName[arraySize]Examples are:int inNumbers[20]; an array called inNumbers of 20 integers.char inName [20]; an array called inName of 20 characters.

Feb 2009 69 OUCS

Page 77: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

float ExamMarks[5] = {0}; an array called ExamMarks of 5 float with all elements explicitly initialised to zero.

const int size = 5; declaring a constant variable size . float ExamMarks[size]; When the constant variable size is applied to the array declaration the number of elements is set to 5. This cannot be changed during runtime of the program. However, it is handy when the number of array elements needs to be changed. Changing the constant value size changes the number of elements wherever the ExamMarks array is used in the program. int numArray [2] [3] is a multidimensional array with 2 rows and 3 columns.

Note: Arrays have been used in C++ for many years and there will be code you work with that was written before Vectors. Vectors are new in C++ and are preferred to arrays and pointers. Common problems involving accessing past the bounds of an array are avoided when using vectors.

OUCS 70 Feb 2009

Page 78: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 19Creating an array to hold exam results Open project Array from the H:\ Examine how values are written into the array Modify the program to read in 10 exam marks

Task 1Open project Array.dev on the H:\ drive.

Step 1 Compile the program, sorting any compilation errors.

Run the program adding five exam results. The output should be similar to Figure 57.

Figure 57

Feb 2009 71 OUCS

Page 79: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Examine the following statements

double ExamMarks[5] = {0}; This statement declares the array, setting it’s size to 5 elements and explicitly initialising all elements to zero.

cout<<"Enter Exam Mark "<<i + 1<<" "; This statement prompts the user to enter an Exam mark into the array at element i + 1 .

Using the notation i + 1 indicates to the user to enter Exam Mark 1 not exam mark 0 which would be less intuitive.

Array elements are numbered from 0 to n-1. So an array that holds 20 integers will be addressed from element 0 to 19.

ExamMarks[0]…ExamMarks[19] .

The first number will be entered into element [0] . The last into element [19] .

cin>>ExamMarks[i];

This statement reads in the user input and stores the values in the array elements of ExamMarks[i] . i is incremented within the for loop and starts at 0 .

Task 2Modify the program to calculate the highest and lowest numbers in the array.

OUCS 72 Feb 2009

Page 80: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 3Create another project call it Names . The program should read in student names, these will be held in an array.The user should enter three names. The names should be output to screen, see Figure 58.Although not part of the STL, the string class is part of the ANSI C++ standard library and has many useful member functions. (See Appendix 13.1.17, String class).One member function is length(). This is used in Figure 58 to establish the number of characters in each name entered.Modify your program to calculate the number of characters in each name entered and display the results.

Figure 58

Feb 2009 73 OUCS

Page 81: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 4 Create another project call it ArrayNameAge. The program should read in two patient names with their age. The user should be prompted to add the age after the name has been added. The output should be as shown in Figure 59.Modify the program to establish the average age. Output the result.

Figure 59

OUCS 74 Feb 2009

Page 82: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

9.1.2. Searching Arrays with Linear SearchLinear search allows the user to search the array and establish whether the array contains a value that matches a search criteria defined by the user. The search compares each element of the array with the user input. The array is not sorted and this method of searching works well for small arrays. For large arrays linear searching is inefficient and it is necessary to use other forms of array searching after the array has been sorted.

Exercise 20Linear Search Open project LinearSearch from the H:\ Examine how random values are written into the array Modify the program to read in 10 exam marks

Task 1Open project LinearSearch.dev on the H:\ drive.

Step 1 Compile the program, sorting any compilation errors.

Run the program; choose a number between 1 and 100. The output should be similar to Figure 64.

Figure 60

Feb 2009 75 OUCS

Page 83: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Examine the following statements

myArray[i] = (1 + rand()%100); This statement uses the rand function, part of the <cstdlib> header file. rand()%100 produces integers in the range 0 to 99.

The function linearSearch takes three arguments. The array name, the size of the array, the third argument is the search value.

if ( array[j] = = value )

return j;

This selection statement compares each element to the search value. If the search value is in the array the element number is returned to main() otherwise -1 is returned.

The if selection statement if (element != -1 ) in main() is used select the output indicating a successful or unsuccessful search.

OUCS 76 Feb 2009

Page 84: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2Create another program to output a count of the individual numbers held in an array. The numbers in the array should be randomly generated. The output should be as shown in Figure 61.

Step 1 Create a project, call it SearchCountVal.dev

Create a new source file SearchCountVal.cpp

Create a header file SearchCountVal.h

Figure 61Step 2

Write the program, creating an array of random numbers. Create a small array of 15 elements and add random numbers to the array using the rand function. The random numbers should be between 0 and 14 .

Prompt the user to enter a number.

Search the array until the number is found or the end of the array is reached.

Provide an output indicating whether the value is present or not in the array.

Feb 2009 77 OUCS

Page 85: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 3 Create a second array that will store in each element a count of the number of times each randomly generated number appears in the first array i.e. if 10 appears twice in the array of randomly generated numbers, element 10 in the second array should show 2. Make sure your array size is 15 elements and the randomly generated numbers in the first array are between 0 and 14.

Output the contents of the second array to screen as shown in Figure 61

The input and output should be in a loop so the user can test the program repeatedly. Remember to add a statement to terminate the program.

OUCS 78 Feb 2009

Page 86: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

9.1.3. Sorting Arrays with Insertion SortWhen working with large quantities of data in an array you will need to sort the data at some point. This makes searching for information quicker and there are many algorithms available that can be used. In the following exercise you will learn how to sort numbers stored in an array in ascending order.

Exercise 21Sorting an array Create a new project call it project InsertionSortClass Add a header file to the project Examine how an array is sorted Modify the program, creating a source file to use the class

information

Task 1Create a new project call it InsertionSortClass.dev

Step 1 Add the header file InsertionSort.h from the H:\ to the project

Examine the code. The class file is used to sort an array of integers passed from the main() program

The sort works by first looking at array elements sort[0] and sort[1] . If the first two values are in order the program continues otherwise they are swapped.

In the second iteration the program looks at element sort[2] and compares this to sort[1] . If the value in sort[1] is greater than the value in sort[2] the values are swapped. The while loop is then used to compare the value in sort[1] to the value in sort[0].

This iterative process continues until all array elements have been sorted.

Feb 2009 79 OUCS

Page 87: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2Add a new source file to the project call it InsertionSort.cpp

Step 1 Add #include "InsertionSort.h"

Create an instance of the class SortArray myArray;

Create an array of 200 randomly generated numbers, numbers[i] = (1 + rand()%100);

Call the class member function myArray.sortArray(numbers,SIZE);

Output the sorted array cout<<setw(4)<<numbers[i];

See Appendix 13.1.8 for more detail on formatting output.

Figure 62 and Figure 63 show the array before and after sorting.

Figure 62

Figure 63

OUCS 80 Feb 2009

Page 88: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 3 Create a second object, call it yourArray . Create an array of 50 randomly generated integers between 1 and 50. Output this array before being sorted and after being sorted.Output a count of the number of times each number appears in the sorted array.

9.1.4. Multidimensional ArraysMultidimensional arrays with two dimensions (arrays can have more than two dimensions) consist of data arranged in rows and columns, see Table 3. Each element in the array is identified by using two subscripts as shown in Table 3. The first subscript identifies the element row and the second identifies the element column. a[0] [1] identifies a value in Row 0, Column 1.The array in Table 3 contains two rows and three columns and can be called a 2 by 3 array.

Column 0 Column 1 Column 2Row 0 a[0] [0] a[0] [1] a[0] [2]Row 1 a[1] [0] a[1] [1] a[1] [2]

Table 3

A multidimensional (2 by 3) array of doubles is shown in Table 4. Column 0 Column 1 Column 2

Row 0 23.67 67.92 85.57Row 1 12.76 91.32 27.89

Table 4

Feb 2009 81 OUCS

Page 89: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 22Creating a multidimensional array Open project MultiDimenArray from the H:\ and run the

program Examine how values are written into and read from the array Modify the program to read in 5 exam marks and

Task 1Open project MultiDimArray.dev on the H:\ drive. There is one associated file MultiDimArrayMain.cpp

Step 1 Compile the program, sorting any compilation errors.

Run the program adding 2 exam results for each of the two students. The output should be similar to Figure 64.

Figure 64Task 2Examine the code used to write values to and read from a multidimensional array.

Step 1 Examine the following code segments

double ExamMarks[2][2] = {0}; This statement creates a two-dimensional array having two rows and two columns and initialises the elements to 0.

Every element in the array is identified by an element name in the form a[x] [y] , where a is the name of the array, and x and y are the subscripts that uniquely identify each element in a . Notice that the names of the elements in row 0 all have a first subscript of 0 , see Table 5. The names of the elements in column 1 all have a second subscript of 1 .

Note : multidimensional arrays can have two or more dimensions (subscripts). Three-dimensional arrays are uncommon.

Column 0 Column 1Row 0 a[0] [0] a[0] [1]Row 1 a[1] [0] a[1] [1]

Table 5

OUCS 82 Feb 2009

Page 90: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 2 Examine the following code segment used to read values in to the array

for(int row = 0; row < 2; row++)

{

for(int col = 0; col <2;col++)

{

cout<<"Enter Exam Mark No "<<col +

1<<" for student No "<<row +1 <<" ";

cin >> ExamMarks[row][col];

}

cout<<endl;

}

The two for loops work taking one row at a time (the outer for loop) and looping through the columns in that row (the inner for loop). When the marks have been entered for all the columns in row 0, row 1 is selected and values entered for each column cell in row 1.

Table 6 shows how four results would be allocated in a 2 x 2 multidimensional array.

Exam mark 1 Exam mark 2Stud 1 67 71Stud 2 61 58

Table 6

Step 3 Examine the following code segment used to calculate the total of each student’s marks.

if(row ==0) r1total += ExamMarks[row][col];else r2total += ExamMarks[row][col];

r1total is a variables to hold the sum of values in column 0 and 1, for row 0 (Stud1). r2total sums the values in the columns for row 1 (Stud 2).

Feb 2009 83 OUCS

Page 91: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Selection for each row is made with if(row ==0), this is Stud1. If row is not 0 then row must be 1 and the mark can be added to r2total. If three exam marks were input per student the code for selecting the marks would need to change.

Task 3Modify the program to read in 5 exam marks for four students.Establish the highest, lowest and average mark for each student. Output the results.Establish the highest and lowest marks overall.Output the results.

Task 4 Create a new project call it MatrixManipulation. This program will manipulate a matrix of integers. Each row of data is totalled and appended to the row. Each column of data is totalled and appended to the column.The sum of the contents of the entire array are calculated and added between the row and column totals

Step 1 A multi-dimensional array has been created and initialised with 80 integers. This is held in the file matrix.txt on the H:\ drive. Add this to your program.

The output from the program should be the same as shown in Figure 65.

Figure 65

OUCS 84 Feb 2009

Page 92: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

9.1.5. Declaring and using vectorsVectors are declared indicating the type and number of elements in the following way:vector<type>vectorName;vector<type>vectorName(initialSize);vector<type>vectorName(initialSize, elementValues);Examples are:vector<double> inNumbers; a vector called inNumbers with no initial size to hold doubles .vector<char> Name(20); a vector called Name with an initial size 20 to hold characters.vector<int> ExamMarks(4,6); a vector called ExamMarks holding integers with initial size of 4 elements each with the value 6 Note: In previous exercises you have created your own member functions. In the following exercises you will use some of the vector class member functions found in the Standard Template Library (STL). Some of these are begin() , end() , erase() , and size(). See section 13.1.13 for more detail.The STL also includes a large collection of algorithms that manipulate the data stored in containers (vectors are one of several types of container).

You can sort the order of elements in a vector (vec) for example, by using the sort algorithm.sort(vec.begin(), vec.end());

You can find a value (69) in a vector by using the find algorithm.ptr = find(vec.begin(), vec.end(), 69); ptr is an iterator to store the memory location of the element found.You can reverse the order of elements in a vector, for example, by using the reverse algorithm.reverse(vec.begin(), vec.end());

There are two important points to notice about the call to reverse . First, it is a global function (as are find and sort) not a member function. Second, it takes two arguments rather than one and operates on a range of elements, rather than on the container (vector container in this case). With the above examples the range is the entire container from begin() to end() (vec.begin() to vec.end()). reverse , like the other STL algorithms, is decoupled from the STL container classes.

Feb 2009 85 OUCS

Page 93: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

The reverse algorithm can be used to reverse elements in vectors , in lists (another container), and even elements in C arrays .

The following program is also valid in C++.int myArray[]={1,6,20,4};;

reverse(myArray, myArray + 4);

for (int i = 0; i < 4; ++i) /*lets see the reversed array*/cout << "Array[" << i << "] = " << myArray[i];

In the above example the first argument to reverse is a pointer (pointers are covered in Section 11 but for now we can say the first argument points to the address in memory that is the start of the vector) to the beginning of the range, and the second argument points one element past the end of the range. This range is denoted (myArray, myArray + 4); Arguments to reverse are iterators , which are a generalization of pointers which is why it is possible to reverse the elements of a C array using the array address and pointer notation.

OUCS 86 Feb 2009

Page 94: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 23Creating a vector to hold exam results Open project Vector from the H:\ Examine how values are written into a vector Modify the program to read in additional exam marks Modify the program to remove exam marks

Task 5Open project Vector.dev on the H:\ drive. There is one associated file Vector.cpp .

Step 1 Compile the program, sorting any compilation errors.

Run the program adding five exam results. The output should be similar to Figure 66.

Figure 66

Feb 2009 87 OUCS

Page 95: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Examine the following statements

#include <vector>; This statement includes the header file <vector> enabling the program to use the class template vector . (templates allow the use of generic functions that admit any data type as parameters and return a value, more on this later.).

vector <double> ExamMarks (5); This statement declares the vector to hold doubles and sets the initial size to 5 elements.

Note: Although vectors can grow to any size it is good practice and more efficient to specify the size when this is known. When no size is given and the contiguous memory spaces have been exhausted the elements must be copied to a larger memory space to increase the size of the vector.

cin>>ExamMarks[i]; This statement reads in the user input and stores the values in the vector slot i of ExamMarks[i] . i is incremented within the for loop in a similar way as in the previous array exercises using the subscript operator [ ] .

Task 6Open Vector.txt from the H:\ . Copy the code and add it to Vector.cpp

Step 1 Copy the code from Vector.txt and add it to Vector.cpp immediately above the statement system("PAUSE");

Run the program entering 5 numbers. Follow the prompts and add an additional number to the vector. The output should be as shown in Figure67.

Examine the following statement

ExamMarks.push_back(test);

push_back() is a member function of the vector class that adds an additional vector element at the end and passes the variable test as a parameter to the vector. The size of the vector is now six elements.

OUCS 88 Feb 2009

Page 96: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Figure 67

size() is a member function of the vector class. It can be used to establish the size of a vector.

The statement for(int i = 0; i < ExamMarks.size(); i++) uses the vector member function size() available to the vector ExamMarks to obtain the size (number of elements) in the vector. The size of the vector is used to identify a terminating value that ends iteration of the for loop.

Task 7Modify the program to delete the last element and output the vector slots showing all values. pop_back() is the member function that can be used to delete the last element in a vector.

Feb 2009 89 OUCS

Page 97: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 8 Create a new project call it VectorSort.dev .In the program create a vector of 100 randomly generated numbers.Output the contents of the vector before and after sorting.See Appendix 13.1.13 for more detail on vectors.

OUCS 90 Feb 2009

Page 98: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 24Create a vector of objects Create a new project that will allow the user to input details of

research done on penguins. Detail will initially be kept on the penguin type and colour; more detail will be collected later.

There are many types of penguin and the data for each type will be kept in instances of a class and the objects stored in a vector.

Task 1Create a new project call it VectorofPenguins .Create a header file Penguins.h and add member functions to allow the user to add and change the penguin type and colour.Add the necessary constructors and destructors including a default constructor that will name a type as "King" with a colour "Black, Grey & Orange" when called. You will need data members to store these values.In main() add a vector to store each object instantiated. Add two objects using code similar to that shown in step 1 then add another penguin object using vector member functions.Output the contents of the vector to screen, it should be similar to Figure 68.

Step 1 In main() create a vector of penguin objects:

vector<Penguins> myPenguin(2);

Loop through the vector adding two objects

for(int b = 0; b < 2; b++){ //Read in the penguin type and colour /*create first object*/myPenguin[b] = Penguins(name, colour);

}

Figure 68

Object member functions can be accessed using the following notation.

cout<<myPenguin[a].getName()

Feb 2009 91 OUCS

Page 99: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 25Using the insert() member function and iteratorsOpen Insert.dev and examine the program. Identify how the insert() member function is used to add data to a vector at any vector element position.Learn how to insert vector data to another vector using the insert() member function.Add an array to a vector using the insert() member function

Task 1Open Insert.dev .Only parts of the program are explained as much of the program has been covered in previous exercises. Important areas of the program are explained in the steps.

Step 1 Examine the code shown in Figure 69

Figure 69

This statement creates an iterator that is used to access members of the vector.

Iterators are used to access members of the container classes (the container type vector in this case), and can be used in a similar manner to pointers (see Sec 11).

In the example shown in Figure 71, iterator it is used with the insert() function to place the value (200) at the beginning of the vector nums .

Examine the code shown in Figure 70

Figure 70

This statement uses the vector member function begin() to initialise the iterator it with the address of the start of the vector.

Examine the code shown in Figure 71

Figure 71

This statement uses the member function insert() and iterator it to insert 200 at the beginning of the vector (it).

Note that an iterator is returned by the function insert() that points to the newly inserted element.

OUCS 92 Feb 2009

Page 100: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Examine the code shown in Figure 72

Figure 72

This version of the insert() function takes 3 arguments and is used for copying in part or full another collection. This may be a vector, a plain C++ array or some other collection that is accessed using pointers/iterators.

This statement inserts a second vector (numsTwo) into nums . The three parameters are: (copy to nums+1 , from start of numsTwo , to end of numsTwo)

Examine the code shown in Figure 73

Figure 73

This version of the insert() function takes 2 arguments. The iterator it + 2 points to element number three. it points to the beginning of the vector and the 2 moves two elements in. The value 696 is inserted at that element.

Examine the code shown in Figure 74

Figure 74

Function Display is passed a reference to a vector and outputs the vector contents used throughout program.

Feb 2009 93 OUCS

Page 101: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2 Add the code shown in Figure 75 to the program and using the insert() member function add the array to the nums vector. Output the contents of the nums vector to screen.

Figure 75

9.1.6. Declaring and using listsLists are a kind of sequence container similar to vectors. The elements of a list are ordered following a linear sequence with storage handled automatically by the class.List containers are implemented as doubly-linked lists and it is worth noting that elements may be in different and unrelated storage locations. Ordering of a list is kept by a relationship to each element of a link to the element preceding it, and a link to the element following it. Because linking information is associated with each element (possibly to different and unrelated storage locations) extra memory may be used to keep the linking. This may be important when using a large list.lists tend to perform better than vectors at inserting, extracting and moving elements in any position within the container but lack direct access to the elements by their position and because of this have a slower access time than vectors. Access to an element has to be via a known position (the beginning or the end) and there is a time cost in linking between the known position and the element to be accessed.

lists are declared indicating the type and number of elements in the following way:

list<type> listName;list<type> listName(initialSize);list<type> listName(initialSize, elementValues);

Examples are:list<double> inNumbers; a list called inNumbers with no initial size to hold doubles .list<char> Name(20); a vector called Name with an initial size 20 to

hold characters.list<int> ExamMarks(4,6); a vector called ExamMarks holding integers with initial size of 4 elements each with the value 6

OUCS 94 Feb 2009

Page 102: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Note: In the following exercises you will use some of the list class member functions found in the Standard Template Library (STL). Some of these are begin() , end() , sort() , and swap(). See section 13.1.15 for more detail.The STL also includes a large collection of algorithms that manipulate the data stored in lists.

Feb 2009 95 OUCS

Page 103: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 26Merging lists Open project Merge from the H:\ Examine how values are written into a list Modify the program to copy lists

Task 1Open the Merge.dev project and examine the program works.

Step 1 Examine the statement shown in Figure 76

Figure 76This statement creates two lists to hold doubles, listOne and listTwo .

Examine the statement shown in Figure 77

Figure 77This statement creates a third list and initialises it with two elements each holding 9.69.

Examine the statement shown in Figure 78

Figure 78This statement creates an iterator for looping through lists. The iterator type for a list is bidirectional. Note that the iterator type for a vector is random access.

The twelve statements following the iterator declaration use the class member function push_back() to add new elements at the end of each list.

The push_back member function is common to vectors and lists.

OUCS 96 Feb 2009

Page 104: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Examine the statement shown in Figure 79

Figure 79This statement uses member function sort() to sort listOne.

Note that lists do not use the sort algorithm that we used with the vector class as the sort algorithm only works with random access iterators, the type used with vectors. Lists use bidirectional iterators so there is a member function we can use (listOne.sort() ).

Step 2 Examine the following statements

Figure 80list iterator it is used to loop through the elements of the list.

listOne.begin() returns an iterator to the beginning of the list.

listOne.end() returns and iterator to the end of the list.

it and the dereference operator * are used to output the values in the vector, *it .

Examine the following statement

Figure 81This statement merges the second list into the first list. All the elements of the second list are inserted into the first list at their respective ordered positions.

NOTE: This empties the second and increases the size of first list.

Feb 2009 97 OUCS

Page 105: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2 In this task you are asked to modify mainMerge.cpp to copy the contents of listTwo to listThree . Note that copy is an algorithm not a member function of the list class.

Step 1 Resize listThree to the same size as listTwo using the list member function resize() so that the list can hold all the elements copied. Arguments to resize will be the size of listTwo . Use the listTwo member function size() to get this value.

Copy the contents of listTwo to listThree

The syntax for the copy algorithm is:

iterator copy( iterator start, iterator end, iterator destination );

The return value ‘iterator’ is an iterator to the last destination element copied.

OUCS 98 Feb 2009

Page 106: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

10 More on FunctionsFunctions are used to encapsulate a set of operations and return information to the main program or calling routine. Encapsulation is data, information or detail hiding. Once a function is written, the detail of how it works is not important to the end user. The user needs to understand what data to input and what output will be produced.

10.1.1. Multiple arguments and default values

In the following exercise you will pass multiple arguments to a function. The arguments must be specified in the prototype, each argument is separated by a comma. The exercise will also detail how to add default arguments in the prototype.

Feb 2009 99 OUCS

Page 107: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Exercise 27Functions with multiple arguments and default values

Write a program to calculate take home pay using functions and default argument values

Task 1Create a new project call it Salary.dev . Name the source file Salary.cpp . The program should read in a gross salary and rate of Income Tax (IT). The salary, IT and National Insurance rate (NI) will be passed to a function to calculate and display the take home pay. Take home pay is calculated as follows: TakeHomePay = (grosspay*(1-NI))*(1-Income Tax)

Step 1 The function prototype you create should be similar to void CalcSalary(double grossSal, double IT, double NI = 5.0);

Note: In this prototype we are passing multiple arguments. Each argument is separated by a comma. A default argument double NI = 5.0 has been also used in the prototype above. Default arguments must be declared at the end of the list of arguments.

Because we are using a default argument for the national insurance rate it is only necessary to read in a gross salary and the rate of income tax. Gross salary and income tax are passed to the function from main() in the statement CalcSalary(grossSal, IT); along with the default NI argument specified in the prototype. All three arguments are used in the function to calculate the take home pay.

Remember, default arguments must be declared at the end of the list.

Step 2 Create a function call it calcSalary

The function will receive three arguments, the definition is shown below

void CalcSalary(double grossPay, double IT, double NI)

The formula for calculating the take home pay is: TakeHomePay = (grossPay*(1-NI))*(1-IT);

IT is the income tax rate read in as a percentage, and NI is the rate of national insurance at 5% as specified in the prototype. The take home pay should be output from within the function.

OUCS 100 Feb 2009

Page 108: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2Modify the program Salary.cpp to read in the gross salaries of five members of staff. Calculate the take home pay and display.Create an object for each member of staff.Create separate member functions to change the rate of NI and Income Tax .

Feb 2009 101 OUCS

Page 109: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

10.1.2. Returning values from functionsOne of the most important aspects of writing programs using functions is that the functions can be reused from one project to the next. In previous programs the output has been from within the function. The functions used in previous exercises should really only be used to compute the change in temperature or calculate take home pay. The result of the calculation should be returned from the function and not output from within the function. Returning values in this way allows the reuse of the function and calculations contained in it.

Exercise 28Returning a value from a function Examine and understand how to return values from a function Modify an existing program Create additional projects

Task 1Open the TemperaturesRetValues.dev project from the H:\ drive and modify the program.

Step 1 Run the program. The output should be the same as shown in Figure 82.

Figure 82Step 2

Examine the function prototype

int FtoCent(int temp, int ch);

This function prototype has a return type of int. When the function is called and calculations completed an integer is returned to the calling statement.

OUCS 102 Feb 2009

Page 110: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 3 Exam the calling statement

retValue = FtoCent(I_far, choice); The function call FtoCent() passes arguments I_far and choice. The value returned is assigned to retValue

Step 4 Examine the function definition. The function definition matches the prototype indicating two integers are being passed to the function and an integer is being returned.

int FtoCent(int ITemp, int ind) {}

Step 5 Examine the function body. The two statements below convert the temperature input. The conversion type required is identified using the user input ind and if selection.

The statement I_far = (ITemp - 32) *5 / 9; is used to calculate the temp in centigrade

The statement I_far = static_cast<int>(ITemp * 1.8 + 32); is used to calculate the temp in farenheit.

The last statement in the function is return I_far; This statement returns the temperature I_far to the calling statement in main().

Note: The data being returned must be the same data type as defined in the function prototype. In this example an integer.

Task 2Open the Salary.dev project you created in Exercise 27 Functions with multiple arguments and default values.

Step 1 Modify the program so take home pay is returned from the function and output to screen from within main() . If you completed Task 2 in Exercise 27 you will need to add a member function of the class to achieve this.

Feb 2009 103 OUCS

Page 111: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 3 Create a new project call it ReturnExperResults.dev The program will read in 5 experimental results. Read the results in to the main program and pass them to a function. The function should calculate the maximum value. This should be returned and displayed within main.

OUCS 104 Feb 2009

Page 112: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Exercise 29Classes and functions Create a class file to calculate the average of results

Task 1Open the project you created in the last task, ReturnExperResults.dev, Exercise 28Task 3.Create a class call it Experimentresults in a new file called ReturnExpResults.h. The values read in to main() should be passed to a function called readNumbers( ) in main() . From within the function readNumbers( ) create an object of the class Experimentresults.From within the function pass the values read in to a constructor of the class.The average value should be calculated within class member functions. Use member functions to return values to the calling function.The average mark should be returned to main() from the function readNumbers( ), then output to screen.

Feb 2009 105 OUCS

Page 113: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

10.1.3. Passing Arrays to FunctionsTo pass an array to a function, it is only necessary to pass the array name and the number of elements in the array. The array name is the position in memory of the first element. The number of elements is passed to enable the function to establish the array size.An array declared as double TempReadings[10]; would require a function call, FunctionName(TempReadings, 10);

Exercise 30Passing Arrays to functions Write a program to pass an array to a function Read values into the function Calculate the average of values read in Output the array values from within main()

Task 1Create a new project call it ArrayReturnValue.dev . Pass an array to a function and read in five numbers. Calculate the average value in the array, return this to main() and output to screen.At the end of the program output the values in the array from within main().

Step 1 Create a new project call it ArrayReturnValue.dev

Create a function prototype double calcAverage(double ExamMarks[], int num);

ExamMarks[] is the array being passed. As with passing variables, it is not strictly necessary to pass the name of the argument, just its type. This could have been written as calcAverage(double [], int num); However, it is useful for future reference as it helps explain how the function works.

It is also necessary to pass the size of the array. num is the number of elements in the array, it’s size.

Step 2 Within main() declare the array and initialise the elements to zero with the following statement double ExamMarks[5] = {0};

This declaration explicitly initialises the first element to zero and implicitly initialises the remaining four to zero

OUCS 106 Feb 2009

Page 114: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 3 Create a function double calcAverage (double ExamMarks[], int num) { }

Read in the values and calculate the average

Add the code to establish the average of values in the array

Return the average value to main() and output

Step 4 Call the function from within main() with the following statement

average = calcAverage(ExamMarks, 5);

Step 5 At the end of main() add the statements

for(int i = 0; i < 5; i++)

(19) cout<<"Exam Mark Number "<<i + 1<<" is "<<ExamMarks[i]<<endl <<endl;

(20)

Step 6 Explain how it is possible at the end of the program to output from within main() all the values in the array entered within the function

In previous exercises when parameters (variables) were passed to functions the function received a value . When a value is used in a function a copy is stored in a part of memory that only exists from the time the function is called to when it ends. After this, the memory and any value in it are lost.

However, the array in this exercise was initialised in main() with zeros and then passed to the function. Data was then added to the array and calculations done. At the end of main() the values in the array elements are output. The array contains values input from within the function.

When the function is called calcAverage(ExamMarks, 5) the name of the array, ExamMarks is passed.

Feb 2009 107 OUCS

Page 115: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

The name of the array is the address in the computer memory of the first element of the array. As the starting address is passed (the name of the array), the called function knows where the array is stored in memory.

Because we are working with memory addresses (references ) any changes made to array elements in the function affect the memory location set up in main() for the array.

C++ passes arrays to functions by reference (to the memory location of the first element). In previous exercises functions were passed values , copies of the variables in main() .

Task 2 Modify your program so that the calculations are done in a class file. Pass the array to the class using a constructor.

Task 3 Go back to Exercise 21 and modify the header file to sort the array passed using the global vector function sort().You should be able to replace the whole member function functionality with one statement.Note that you will have to change the class member function name from sort to another name. Defining a member function name the same as a vector function name will cause a compilation error.Choose your own function name or use sortArray() .

OUCS 108 Feb 2009

Page 116: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 4 Continuing from the previous task, when you have sorted the array add another member function to reverse the array.Call the new member function and check the array has been reversed.

Feb 2009 109 OUCS

Page 117: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

10.1.4. Passing Two-dimensional Arrays to FunctionsIt is common to want to store numbers in a two dimensional layout of rows and columns as shown in Table 7.

1876.45 7834.73 2983.728712.23 6293.99 5612.01

Table 7

This arrangement is known as a two-dimensional array or matrix.C++ uses an array with two subscripts to store a two dimensional array. double Balance[2][3];

When we specify a one-dimensional array the number of elements must be given. When a two-dimensional array is specified it is necessary to specify the array elements in both dimensions. We therefore specify the number of rows and columns. The Balance array in the statement above has two rows and three columns.

Exercise 31Multi-Dimensional Arrays and functions Write a program to pass a multi-dimensional array to a function Read bank deposits in Calculate the deposits, interest and total capital for all

customers Output the array values from a function

Task 1Create a new project call it ArrayMultRetVal.dev. The program will read in bank account deposits for two customers and output the balance of accounts. The customer will be prompted to enter deposits and these will be stored in a

Figure 83

OUCS 110 Feb 2009

Page 118: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

two-dimensional array.

The output to screen will show the total sum invested, the interest accrued and the balance after addition of interest for each customer.The last line of output will show the overall sum of all accounts before interest is added, the sum of all interest and total balance for each customer. See Figure 83.The array will be declared in main() and passed to two functions.The first function will be used to get user deposits, the second to do the calculations and output to screen.

Step 1 Before main() create a function prototype,void getDeposits(double Balance[][colSize],int ); This statement indicates there is a function that will be passed a 2 dimensional array with 3 columns. The number of rows and columns is determined within main() .

Create a second prototype void passBalances(double Balance[][colSize],int );This is used to do calculate balances and output to screen.

Declare two constants for the rows and columns before the function prototypes.

const int rowSize =2;const int colSize =3;

the const qualifier can be used to declare a constant variable rowSize to 2. Note: constant variables must be initialised and cannot be changed. These are declared outside main() and can be seen by all functions.

within main() declare the array and initialise the elements to zero. double Balance [rowSize] [colSize] = {0};

Create the function getDeposits() after main() . The function definition should be: void getDeposits(double Balance[][colSize],int rS)

{/*add deposits in here*/}

See section 9.1.4 Multidimensional Arrays for detail on how to add the deposits in the function.

Feb 2009 111 OUCS

Page 119: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Create a second function void passBalances (double Balance[][colSize],int rS) after main()

Calculations to establish the interest and balance for each customer should be done in the inner loop (column ) of the array search. The following statements will establish the deposit, interest and total for each deposit

deposited += Balance[r][c];

interest +=Balance[r][c]*0.05;

total +=(Balance[r][c]*(1 + 0.05));

The calculations to total all deposits need to be done in the outer loop (rows) of the array search

OAdeposited += deposited;

deposited = 0; /*reset the amount deposited for next customer*/

OAinterest +=interest;

interest = 0; /*reset the interest for next customer*/

OAtotal +=total;

total = 0;

Step 3 Call the functions from within main() with the following statements.

getDeposits(Balance, rowSize); /*call function to get deposits, pass array and No Rows*/passBalances(Balance, rowSize);

Task 2 Modify the program you have just created using a class defined in a separate header file. Pass the array to the class object.All calculations should be done within the class file and output via member functions.

OUCS 112 Feb 2009

Page 120: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Feb 2009 113 OUCS

Page 121: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

10.1.5. Overloading functionsWhen the same name is used for more than one function the function name is overloaded. C++ allows several functions to be defined with the same name provided the functions have different sets of parameters. The parameters set can be different kinds, or different number of parameters or a combination of both. When the overloaded function is called the compiler looks at the type and order of parameters before deciding which function to call.

Exercise 32Function Overloading Examine a program to see how functions can be overloaded

Task 1Open the project OverloadingFunctions.dev on the H\: drive and examine the program structure. There is one source file OverLoadingFunctions.cpp.

Step 1 Run the program. The output should be the same as shown in Figure 84.

Figure 84

Step 2 Examine the function prototypes

void FtoCent(int temp);void FtoCent(double temp);

Both prototypes return void and both have the same name. The parameters that are being passed are different, int and double .

OUCS 114 Feb 2009

Page 122: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 3 Exam the statement

inValue = toupper(inValue); toupper is a member function in header file <cctype> that changes the input char to upper case. Using toupper means it is unnecessary to test for upper and lower case values input.

In the selection (if, else if, else ) either an integer or double is read in, then the appropriate FtoCent function called. The compiler differentiates overloaded functions by the function name and order of parameter type. This ensures the proper overloaded function is called.

Step 4 Examine the function definitions.

The two function definitions have the same name but different types of argument. In this example the compiler is selecting the correct function on the single argument type being passed.

Step 5 Examine the function void FtoCent(double ITemp) used to convert a double value read into centigrade.

The statement cout <<fixed<<setprecision(2);

This statement sets the stream manipulators, fixed and setprecision. Another stream manipulator used in this function is setw . The header file <iomanip> must be included to use these stream manipulators.

When several numbers are displayed each is printed with the minimum number of digits needed to show the value. This can produce some unexpected output results.

The width of an output field can be set using a stream manipulator setw . To set the next number to be printed to a width of 5 digits use cout <<setw(5). This command does not produce any output but manipulates the stream to change the output format of the next value. Note : setw must be specified for every item output.

Feb 2009 115 OUCS

Page 123: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

The statement cout << fixed << setprecision(2) << setw(5) << ITemp; sets the precision of the following floating point number to 2 decimal places and the field width to 5.

As fixed and setprecision only have to be used once, the above statement could be written as two statements cout << fixed << setprecision(2); cout << setw(5) << ITemp; avoiding repetition of fixed and setprecision with further statements.

See Appendix 13.1.8 for more detail.

Task 2Modify the program in the previous task so the program can be used to convert temperatures from Centigrade to Fahrenheit as well as from Fahrenheit to Centigrade.

Overload the new function so the user can enter an integer or double to the program.

Step 1 Modify the program OverLoadingFunctions

The formula for converting from Centigrade to Fahrenheit is f = ((9 * c)/5) + 32.0; f is the temperature in Fahrenheit and c is a temperature in Centigrade.

Task 3 Add a class header file to the project. Call it OverLoadingFunctions .h. Modify the program so the calculations are done within a class header file.

OUCS 116 Feb 2009

Page 124: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

10.1.6. Function TemplatesIn the previous section you used overloaded functions to perform similar operations that required different program logic on different data types. When the program logic and operations are the same for all data types it is usual to perform overloading by using function templates.When using templates the argument types passed to the function can be different and C++ automatically generates separate object code functions (function template specialisations) to handle each call in an appropriate way. When a template is used in this way a whole list of overloaded functions has effectively been created and the user can enter any data types to match the number of arguments the function requires. All function templates begin with the keyword template followed by a list of template parameters enclosed in angle brackets template < typename T >. The keyword typename indicates that the value T will be a type and not a value. It can be a primitive type (int) or a class type (string). NOTE: Earlier versions of C++ used the keyword class for this purpose and the template prefix would be written as template <class T>. You can use either but the keyword typename is more descriptive.

Exercise 33Function Templates Examine a program to see how function templates can be used

instead of function overloading

Task 1Open the project FunctionTemplate.dev on the H\: drive and examine the program structure. There are two associated files: FunctionTemplate-Maximum.h FunctionTemplate-Maximum.cpp.

Step 1 Run the program, adding data as requested. The output should be the same as shown in Figure 85

Figure 85

Feb 2009 117 OUCS

Page 125: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Step 2 Examine the header file FunctionTemplate-Maximum.h

template < typename T >

T maximum( T value1, T value2, T value3 )

All function templates begin with the keyword template . The type template parameter T in the function template definition is used to specify the type of argument passed to the function, the return type and any variables declared in the function.

The template parameter T precedes the three arguments being passed, the return type and the variable maximumValue declared in the function.

The other selection statements in the header file are used to establish the maximum value passed to the template function which is then returned to the calling program.

FunctionTemplate-Maximum.cpp is used to prompt the user to enter three integers, three doubles and then three characters. This demonstrates how one template function can be used instead of function overloading when the program logic and operations are the same for all data types.

OUCS 118 Feb 2009

Page 126: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 2 Create another project call it FunctionTemplateArrays.dev.

Step 1 Create two files in the project. A class definition, and the client code.

In the header file create the class ShowArray

In the class create a function template

template < typename T >

void printArray( T array[], int elements )

{ /* start function printArray*/

for(int i = 1; i<=elements;i++)

{ /*start for*/

if(i%5 == 0) /*add a new line after 5*/

{ cout<<array[i-1]<<"\t";

cout<<endl; }

else

cout<<array[i-1]<<"\t";

} /*end for*/

} /* end function printArray*/

Step 2 In main() create three arrays. One with 45 randomly generated doubles, one with 45 integers and one with 10 strings.

Create an object of class ShowArray with the statement ShowArray myShowArray;

Call the template function passing the three arrays in turn.

This shows that when the program logic is the same for all data types function templates can be used for function overloading. See Figure 86.

Feb 2009 119 OUCS

Page 127: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Figure 86

OUCS 120 Feb 2009

Page 128: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

11 Pointers

In C++ programming data (variables) can be referenced by pointing to the address of a memory location.A pointer variable contains the address (location in memory) of a data variable. This can be particularly useful when working with arrays as the elements in an array will always occupy consecutive memory places. Incrementing the pointer variable by one, addresses the next array element.

Declarations:int C; This is a standard variable declaration C, that contains a value as yet unknown of type int.int *C; This is a pointer C, that will point to an address in memory containing a value of type int. Each variable declared as a pointer must be preceded by an asterisk (*) the dereference operator . int *age, height; age is a pointer, height is a value.double *far, *cent; are both pointers to double values.Pointers must be initialised when they are declared, or in an assignment. It is common to initialise pointers to a memory address but they can also be initialised to zero. A pointer pointing to 0 is called a null pointer.Note:When the * dereference operator is used in a variable declaration it indicates the variable being declared is a pointer and not a value .But do beware, when the * dereference operator appears before a pointer variable elsewhere in the program it references the data stored at the address of that pointer.To complicate matters further using the pointer name without the dereference operator in the program references the address in memory.

11.1.1. Initialising pointersPointers can be initialised in two ways. int x = 16, y = 69; /*variable declaration and initialisation*/

1: int *x_ptr = &x; /*pointer declaration and initialisation. xptr points to the address of x*/

Feb 2009 121 OUCS

Page 129: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

2: int *y_ptr; /*pointer declaration. yptr is a pointer .*/ y_ptr = &y; /*Pointer initialisation. yptr points to the

address of y. */

Once declared, a pointer variable can be assigned the address of another variable using the & “address of operator”. Note: the variable name should not be prefixed by the * dereference operator in the assignment statement unless the pointer is initialised immediately in the variable declaration, item 1 above.

Exercise 34Using pointers Open project Pointers from the H:\ Examine the structure of the program

Task 1Open the project Pointers.dev on the H:\ drive. There is one associated file, PointersMain.cpp.

Step 1 Compile the program, sorting any compilation errors.

Run the program. The output should be the same as Figure 87.

Figure 87(21)

OUCS 122 Feb 2009

Page 130: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Step 2 Examine the following statements. Only the important parts of the program are explained, the rest has been covered in previous exercises.

int *x_ptr = &x; This is x_ptr pointer declaration and initialisation.

int *y_ptr; Declaring another pointer y_ptr .

y_ptr = &y; Initialising y_ptr .

y_ptr = x_ptr; Assigning x_ptr address to y_ptr . Both pointers are pointing to variable X (16) .

y_ptr = &y; Assigning the address of y back to pointer y_ptr .

*y_ptr = 170; Assign 170 to the variable at memory location of y_ptr . y_ptr points to variable y so 170 has been assigned to y .

11.1.2. Pointer Arithmetic and ArraysWe have seen that once a pointer is initialised it has a memory address and this address can be reassigned another address. It is also possible to change an address using standard arithmetic.The ++ and -- , increment and decrement operators can be used to move the pointer along to the next, or back to the previous memory address. To jump more than one memory address you would have to use the assignment operators += and -=. When using arrays and pointers the array name is the address of the first element in the array. int intArray[] = {1,2,3,4,5};

int *x_ptr = intArray;

The pointer has been declared and initialised with the statement int *x_ptr = intArray; Note: there is no need to use the address of operator & when initialising arrays as the array name is the address of the beginning of the array. When working with arrays each element of the array will be the type and size at declaration. When an array is declared to hold integers, each element will be 4 bytes in size. An array of doubles will have element sizes of 8 bytes.

Feb 2009 123 OUCS

Page 131: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

It is not important to know how many bytes make up each element. Moving the pointer through the array with the assignment operator x_ptr += 2 will move two elements further through the memory allocated for the array, or 16 bytes for an array of doubles.

Exercise 35Pointers and Arrays Open project PointerArithmetic from the H:\ Examine the structure of the program

Task 1Open the project PointerArithmetic.dev on the H:\ drive. There is one associated file, PointerArithmeticMain.cpp.

Step 1 Compile the program, sorting any compilation errors.

Run the program. The output should be the same as Figure 88.

Figure 88Step 2 Examine the following statements in the program. Only the important parts of the program are explained, the rest has been covered in previous exercises.

int *x_ptr = intArray; this is the pointer declaration and initialisation. Note: The name of the array is the address of the first element.

for (i = 1; i<5;i++){

x_ptr++; cout <<"The VALUE stored in ELEMENT "<<i+1<<" is " <<*x_ptr <<endl;

}

OUCS 124 Feb 2009

Page 132: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

The statement x_ptr++; (Note: there is no dereference operator therefore x_ptr is pointing to a memory address) moves the pointer one address further along the array

*x_ptr the dereference operator is used outside a variable declaration so it is referencing the value at a memory location.

x_ptr--; (there is no dereference operator therefore the pointer is pointing to a memory address) moves the pointer one address back along the array. As this statement is in a for loop that repeats four times the pointer has been moved back to the beginning of the array.

The statement x_ptr +=4; moves the pointer four addresses further into the array. The value there will be the value in the last element in the array, 5.

Task 2Create a new project call it ReverseArray.dev .

In main() create an array of 20 random numbers of type double.

Pass the array to a class constructor.

Using only pointers reverse the values in the array of twenty doubles.

Output the reversed array from within main() .

Task 3 Create a new project call it Array_Algorithm.dev.Use STL global functions to manipulate an array.

Step 1 Open Array_Algorithm.txt on the H:\

Replace the default source file in the project with Array_Algorithm.txt

Add the necessary code so the output is the same as that shown in Figure 89.

Feb 2009 125 OUCS

Page 133: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Figure 89

The array can be reversed using the algorithm reverse() and pointers to the beginning and end of array. A in place of iterator vec.begin() and A + 6 in place of vec.end() .

reverse(A, A + 6); A identifies the first element in the array, it points to the first element. A + 6 points to the last element. Because reverse is decoupled from the STL container classes and works on a range of elements we are able to use pointers in place of the iterators vec.begin() and vec.end().

Sort the array using the sort algorithm sort() and pointers to the beginning and end of array A .

Search the array and store the address if found.

ptr = find( A, A + elements, numToFind ); /*ptr pointer stores location*/

Check if pointer ptr is past end of the array: if(ptr = = A + elements) and if it is tell the user.

If the pointer ptr is not past end of array, the number is there. Output the value using pointer notation *ptr .

See section 13.1.13 for more information on vectors and global functions.

OUCS 126 Feb 2009

Page 134: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Task 4 Now you have seen how to find values in an array go back to Exercise 21 and add functionality in a new member function to allow the user to search for numbers repeatedly until they end the program. See Figure 90.

Figure 90

Feb 2009 127 OUCS

Page 135: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

12 Classes and Interfaces12.1.1. Interfaces

The interface of a class defines the services a class’s objects can use and how to request the services. Interfaces do not contain detail of how the class works.In the programs you have been writing the class definition in the .h files contain the complete definitions for the member functions and the declarations of the private data members. It is considered better practice to define the member functions separately as function prototypes that describe the class’s public interface. The data members of the class are also defined in the interface as memory has to be allocated for each data member.The detail member functions implementation, or how they work, is in a separate source code file.

Exercise 36Creating an Interface Open an existing project Modify a header file Create an interface

Task 1Open an existing project. There should be two associated files: Header.dev and OxStudents.h . Modify the header file to create class definitions.Create an additional file detailing the member function definitions that represent the implementation of the class.

Step 1 Open project Header.dev on the H:\ If you do not have this project, go back to Exercise 13 and complete the task.

Add a new Source file to the project, File | New | Source File

Save and name the file OxStudents.cpp

Step 2 Copy the class definition code from OxStudents.h file and paste it into the OxStudents.cpp file.

Change the code in OxStudents.h so there is no implementation, see Figure 91

OUCS 128 Feb 2009

Page 136: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Figure 91Step 3

Add the directive #include "OxStudents.h" at the top of OxStudents.cpp

Compile the program

You should get a compilation error indicating a redefinition of class OxStudents. The class has already been defined in the .h file and a class cannot be defined twice.

Step 4 Remove the class definition by removing the line class OxStudents and the closing curly brace and semi-colon at the end of the file

Remove public:

Change the function headers to match Figure 92 .

Figure 92Notice that displayName is now preceded by the class name, OxStudents and :: the binary scope resolution operator . The member function is now related to the separate OxStudents class definition that contains the class data members and member function definitions.

Compile and run the program

Feb 2009 129 OUCS

Page 137: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Task 2 Go back to the other files you have created and add interfaces to these projects.

OUCS 130 Feb 2009

Page 138: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

13 Appendix13.1.1. Arithmetical Operators

Operator Operation+ Addition- Subtraction* Multiplication/ Division% Modulus

++ Increment-- Decrement

13.1.2. Assignment Operators

Operator Example Equivalent= a = b a = b

+= a +=b a = a + b-= a -=b a = a - b*= a *=b a = a * b/= a /=b a = a / b%+ a %=b a = a % b

Feb 2009 131 OUCS

Page 139: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

13.1.3. Assignment and Arithmetic examples

The assignment operator in C++ is =. The format is variable = expression; this can be read as, assign to the variable the value of the expression . An example to calculate the number of pence in a value in pounds would be:pence = pounds * 100;Note: it is easy to confuse the assignment operator = with the equals notation used in mathematics. The equals notation in C++ is ==.

Incrementing a variable.month = month + 1; adds the value one to the variable month. This can be written as month++;

Decrementing a variable.month = month - 1; deducts the value one from the variable month. This can be written as month--;

In C++ it is also possible to combine arithmetic and assignment operations.

To add 2 to a variable total: total = total + 2; or total +=2;

To subtract 2 from total:total = total - 2; or total -=2;

To multiply total by 2:total = total * 2; or total *=2;

13.1.4. Relational and Equality Operators

The equality operator is used to compare two operands (a == b) and returns 1 (true) if both are equal, otherwise 0 (false) is returned.The inequality operator (!=) returns 1 (true) if both are NOT equal, otherwise 0 (false) is returned.Both the above operators are commonly used to test the state of two variables to perform conditional branching.

OUCS 132 Feb 2009

Page 140: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

The relational operators also return either true or false. (a >= b) returns 1 (true) if a is greater than or equal to b, otherwise 0 (false) is returned.

Standard algebraic equality or relational operator

C++ equality or relational operator

Sample C++ condition

Meaning of C++ condition

Relational operators> > a>b a is greater than b< < a<b a is less than b

>= a >= b a is greater than or equal to b

<= a <= b a is less than or equal to b

Equality operators= == a == b a is equal to b

!= a != b a is not equal to bTable 8

13.1.5. Logical Operators

When using if selection statements it is common to use the relational operators as part of the test. if(num >5), if(size<=14), if(Char == ‘A’). These are fine for testing one condition.To test multiple conditions it is possible to nest if statements but this can be a bit cumbersome.Logical Operators can be used to form more complex conditions by combining simple conditions.

Logical AND (&&) Operator allows a test to see if two conditions are true.if (leaveBooked > LeaveLeft && staffCover = = false)

cout<<”Take your holidays sometime else”;

Logical OR (||) Operator allows a test to see if either or both of the conditions are true.if (Temperature < 16 || windspeed > 15)

cout<<”Too cold or windy to sunbath today then”;

Feb 2009 133 OUCS

Page 141: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Logical Negation (!) Operator reverses the meaning of a condition.if (!(windspeed == 20))

cout<<”The wind speed is not 20 it’s ”<<windspeed;

This could be written equally as well with the equality operator,if (windspeed != 20)

cout<<”The wind speed is not 20 it’s ”<<windspeed;

OUCS 134 Feb 2009

Page 142: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

13.1.6. Escape Sequences

Escape Sequence

Description

\n Newline. Position the screen cursor at the beginning of the next line.

\t Horizontal tab. Move the cursor to the next tab stop.

\r Carriage return. Position the cursor at the beginning of the current line.

\a Alert. Sound the system bell.\\ Backslash, used to print a backslash.\’ Single quote. Use to print a single quote

character.\” Double quote. Used to print a double quote

character

13.1.7. Cast OperatorIs where the programmer explicitly asks for a change in data type. It may be that the result of a calculation is a double and the user wants it to be of type integer. A double can be cast to an integer in the following way:double aNum = 23.7;

int anInt = 0;

anInt = static_cast<int>(aNum);

13.1.8. Formatted OutputWhen several numbers are displayed each is printed with the minimum number of digits needed to show the value. This can yield some unexpected output. The width of an output field can be set using a stream manipulator. To set the next number to be printed to a width of 5 digits use cout <<setw(5). This command does not produce any output it manipulates the stream to change the output format of the next value. Note: setw must be specified for every item output.To use any stream manipulators you must include the header #include <iomanip>. setprecision is another manipulator and is used to set the precision of the next floating point number. Note: setprecision only has to be set once as the stream remembers the formatting directive and

Feb 2009 135 OUCS

Page 143: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

does not affect integer fields. The format is cout << setprecision(3) .To set precision for trailing zeros (0.100 will appear as 0.1) it is necessary to use the fixed format. The notation is: cout << fixed; Note: fixed only has to be set once.The three manipulators can be combined to achieve the required precision and field width when used in this way:cout << fixed << setprecision(3) << setw(5) << myDouble; Alternatively as fixed and setprecision only have to be set once this statement could be written as:cout << fixed << setprecision(3);

cout << setw(5) << myDouble;

13.1.9. Header FilesEvery program that you create will have at least one header file. If you use input or output you will have to include the iostream header.If you use mathematical functions you will need cmath. It can be difficult to know which header files to use for each function. Some of the common header files used, together with some of the older ones you may find with inherited code are shown below. It is a good idea to use the help if you are unsure which header files are associated with particular functions.

Standard C++ header Old headeriostream iostream.hiomanip iomanip.hfstream fstream.hcmath math.hcstdlib stdlib.hstring No equivalentvector vector.h

Table 9

13.1.10. Scope

The portion of a program where an identifier can be used is known as its scope.An identifier declared outside any function or class has file scope . This type of identifier is “known” by all functions. Global variables and function prototypes all have file scope.

OUCS 136 Feb 2009

Page 144: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Identifiers declared inside a block of code have block scope . This type of scope begins at the identifiers declaration and ends at the termination right brace (}) of the block in which the identifier is declared.Any block can contain local variable declarations. If blocks are nested it is possible to declare variables with the same name in each nested block. The variable in the outer block is hidden while the inner block is being executed.

Feb 2009 137 OUCS

Page 145: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

13.1.11. Enumerating constants

The enum keyword provides a handy way to create a sequence of integer constants. An example of enumeration is shown below:enum Months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

Each of the constants will have a default value 1 greater than the constants that it follows in the list. The first value in the enumeration above is explicitly set to 1 and the remaining values increment by 1. The values assigned from JAN to DEC will be 1 to 12.The statement cout<<"DECEMBER is month number "<<DEC <<endl; would be output as DECEMBER is month number 12 .

13.1.12. Constants

Data that will not change during the execution of a program should be stored in a constant container rather than a variable. If the program attempts to change the value stored in a constant the compiler will report an error and compilation will fail.Constant can be created for any data type by prefixing the declaration with const keyword followed by a space. Note: Constants must always be initialised at declaration.The following declaration declares a constant for the speed of sound at sea level m/s.

const double SpeedOfSound = 340.29;

13.1.13. Vector member functions

Some commonly used member functions of the vector class are:

Vector member Functions

Effect

at(element number) Gets the value contained in the specified element

back() Gets the value in the final elementbegin() Points to the first element in vectorclear() Erases the vectorempty() Returns true (1) if the vector is empty,

or false (0) otherwise

OUCS 138 Feb 2009

Page 146: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Vector member Functions

Effect

end() Points to the last element in vectorfront() Gets the value in the first elementinsert() Insert new elements before positionpop_back Removes the final elementpush_back(value) Adds an element to the end of the

vector, containing the specified valuesize() Gets the number of elements

13.1.14. Global functionsGlobal functions are not member functions. They take more than one argument and operate on a range of elements rather than on the vector container, i.e. they can be used on other types of containers.

Vector global Functions Effectfind(); ptr = find(v.begin(), v.end(), 67);

Finds the element in the vector containing number 67. Needs iterator (ptr) to store location of element.

reverse();reverse(v.begin() v.end())

Reverses the values in a vector (v)

sort(); sort(v.begin(), v.end())

Sorts the vector (v)

13.1.15. list member functions

Some commonly used member functions of the list class are:

list member Functions

Effect

back() Gets the value in the final elementbegin() Points to the first element in vectorclear() Erases the vectorempty() Returns true (1) if the vector is empty,

or false (0) otherwiseend() Points to the last element in vectorfront() Gets the value in the first elementinsert() Insert new elements before position

Feb 2009 139 OUCS

Page 147: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

list member Functions

Effect

pop_back Removes the final elementpop_front Removes the first elementpush_back(value) Adds an element to the end of the

vector, containing the specified valuesort() Sorts the elements in the container from

lower to highersize() Gets the number of elementsswap() Exchanges the content of the list

13.1.16. cmath functions

Function Argument Result Returned Value

Example Result

ceil(x) double double Smallest integer ≥ x

ceil(2.1) 3.0

cos(x) double double Cosine of x radians

cos(1.0) 0.54

fabs(x) double double Absolute value of x

fabs(-1.5) 1.5

floor(x) double double Largest integer ≤ 2.9

floor(2.9) 2.0

pow(x,y) double double x to the yth power

pow(2,4) 16.0

sin(x) double double Sine of x radians

sin(1.0) 0.84

sqrt(x) double double Square root of x

sqrt(4) 2.0

tan(x) double double Tangent of x radians

tan(1.0) 1.56

OUCS 140 Feb 2009

Page 148: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

13.1.17. String class

The string class defines many member functions . A few of the basic ones are described below:

Initialisation - constructors

form

A string expression string str2 = str1;

A character string literal string Intro = "Programming with C++";

A substring of another string object

string Intro = "Capetown";

string Mytown = "Boars"

string MyTown (Intro,4,5);

starts at character 4 ('t')with a length of 5, (or the rest of the string, if shorter)cout << myTown << endl;

will produce an output “town”

Member Functionslength() string myName = "Sebastion";

myName.length();

will produce an output of 9.insert () Inserts a string into the current

string, starting at the specified position.string myName = " Sebastion";

string nameAdd = "rjio";

myName.insert (2,nameAdd);

cout << myName << endl; will produce an output “Serjiobastion”

erase() Delete a substring from the current string.string myName = " Sebastion";

myName.erase (0,2);

cout << myName << endl;

Feb 2009 141 OUCS

Page 149: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Member Functionswill produce an output “bastion”

replace() Delete a substring from the current string, and replace it with another string.

string myName = " Sebastion";

string aName = "renna";

myName.replace (3,6,aName);

cout << myName << endl;

will produce an output “Sebrenna”

find() Search for the first occurrence of the substring in the current string. If the word is found, return the position of the first character. If not, return -1.

string sName;

string findWord;

position = sName.find(findWord);

substr() Returns a substring of the current string.string myName = " Sebastion";

string aName = myName.substr (0,3);

cout << aName << endl;

will produce an output “Seb”

Non-member functions

getline()string name;

getline(cin, name);

OUCS 142 Feb 2009

Page 150: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

A number of C++ operators also work with string objects

Operator

=string fString = “Hello”;

string lString;

lString = fString;

Assign a character (char) to a string object.

string aStringC;

aStringC = 'Z';

+Concatenate two string objects.

string str1 = "C++";

string str2 = "Programming";

string str3 = str1 + str2;

+Concatenate a string object and a character string literal.

string str = "Hello ";

string str1 = str + "there";

The same concatenation can be done in this way:

str += “there”;

+Concatenate a string object and a single character.

string str = "Bye Bye";

string strBye = str + '!';

Feb 2009 143 OUCS

Page 151: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

13.1.18. ASCII Character set

Decimal Octal Hexadecimal Binary Value0 0 0 0 NUL (Null char.)1 1 1 1 SOH (Start of Header)2 2 2 10 STX (Start of Text)3 3 3 11 ETX (End of Text)4 4 4 100 EOT (End of Transmission)5 5 5 101 ENQ (Enquiry)6 6 6 110 ACK (Acknowledgment)7 7 7 111 BEL (Bell)8 10 8 1000 BS (Backspace)9 11 9 1001 HT (Horizontal Tab)

10 12 00A 1010 LF (Line Feed)11 13 00B 1011 VT (Vertical Tab)12 14 00C 1100 FF (Form Feed)13 15 00D 1101 CR (Carriage Return)14 16 00E 1110 SO (Shift Out)15 17 00F 1111 SI (Shift In)16 20 10 10000 DLE (Data Link Escape)17 21 11 10001 DC1 (X ON) (Device Control 1)18 22 12 10010 DC2 (Device Control 2)19 23 13 10011 DC3 (X OFF)(Device Control 3)20 24 14 10100 DC4 (Device Control 4)21 25 15 10101 NAK (Negative Acknowledgement)22 26 16 10110 SYN (Synchronous Idle)23 27 17 10111 ETB (End of Trans. Block)24 30 18 11000 CAN (Cancel)25 31 19 11001 EM (End of Medium)26 32 01A 11010 SUB (Substitute)27 33 01B 11011 ESC (Escape)28 34 01C 11100 FS (File Separator)29 35 01D 11101 GS (Group Separator)

30 36 01E 11110 RS(Request to Send)(Record Separator)

31 37 01F 11111 US (Unit Separator)32 40 20 100000 SP (Space)33 41 21 100001 ! (exclamation mark)34 42 22 100010 " (double quote)35 43 23 100011 # (number sign)36 44 24 100100 $ (dollar sign)37 45 25 100101 % (percent)38 46 26 100110 & (ampersand)39 47 27 100111 ' (single quote)

OUCS 144 Feb 2009

Page 152: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Decimal Octal Hexadecimal Binary Value40 50 28 101000 ( (left/opening parenthesis)41 51 29 101001 ) (right/closing parenthesis)42 52 02A 101010 * (asterisk)43 53 02B 101011 + (plus)44 54 02C 101100 , (comma)45 55 02D 101101 - (minus or dash)46 56 02E 101110 . (dot)47 57 02F 101111 / (forward slash)48 60 30 110000 049 61 31 110001 150 62 32 110010 251 63 33 110011 352 64 34 110100 453 65 35 110101 554 66 36 110110 655 67 37 110111 756 70 38 111000 857 71 39 111001 958 72 03A 111010 : (colon)59 73 03B 111011 ; (semi-colon)60 74 03C 111100 < (less than)61 75 03D 111101 = (equal sign)62 76 03E 111110 > (greater than)63 77 03F 111111 ? (question mark)64 100 40 1000000 @ (AT symbol)65 101 41 1000001 A66 102 42 1000010 B67 103 43 1000011 C68 104 44 1000100 D69 105 45 1000101 E70 106 46 1000110 F71 107 47 1000111 G72 110 48 1001000 H73 111 49 1001001 I74 112 04A 1001010 J75 113 04B 1001011 K76 114 04C 1001100 L77 115 04D 1001101 M78 116 04E 1001110 N79 117 04F 1001111 O80 120 50 1010000 P81 121 51 1010001 Q82 122 52 1010010 R83 123 53 1010011 S

Feb 2009 145 OUCS

Page 153: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

TPLO C++

Decimal Octal Hexadecimal Binary Value84 124 54 1010100 T85 125 55 1010101 U86 126 56 1010110 V87 127 57 1010111 W88 130 58 1011000 X89 131 59 1011001 Y90 132 05A 1011010 Z91 133 05B 1011011 [ (left/opening bracket)92 134 05C 1011100 \ (back slash)93 135 05D 1011101 ] (right/closing bracket)94 136 05E 1011110 ^ (caret/cirumflex)95 137 05F 1011111 _ (underscore)96 140 60 1100000 `97 141 61 1100001 a98 142 62 1100010 b99 143 63 1100011 c

100 144 64 1100100 d101 145 65 1100101 e102 146 66 1100110 f103 147 67 1100111 g104 150 68 1101000 h105 151 69 1101001 i106 152 06A 1101010 j107 153 06B 1101011 k108 154 06C 1101100 l109 155 06D 1101101 m110 156 06E 1101110 n111 157 06F 1101111 o112 160 70 1110000 p113 161 71 1110001 q114 162 72 1110010 r115 163 73 1110011 s116 164 74 1110100 t117 165 75 1110101 u118 166 76 1110110 v119 167 77 1110111 w120 170 78 1111000 x121 171 79 1111001 y122 172 07A 1111010 z123 173 07B 1111011 { (left/opening brace)124 174 07C 1111100 | (vertical bar)125 175 07D 1111101 } (right/closing brace)126 176 07E 1111110 ~ (tilde)127 177 07F 1111111 DEL (delete)

OUCS 146 Feb 2009

Page 154: C++ Documentation TPLO 16-02-09 - University of Oxfordbrisbane/…  · Web view · 2009-02-16This handbook accompanies the taught sessions for the course. Each section contains

C++ TPLO

Feb 2009 147 OUCS