Sie sind auf Seite 1von 74

Maths and Computing 2

xx10118






An Introduction to the
C++ Programming Language

http://staff.bath.ac.uk/ensdnj/cpp







Department of
Mechanical Engineering

Issue 7.0, 2005
Introduction to C++ Page 1
Contents
1 INTRODUCTION 3
I.I Abouf fhis course 3
I.Z So whof is o progromming Ionguoge7 4
I.3 Progrom sfrucfure ond pIonning 4
I.4 Furfher reoding 4
Z STARTINS TO PROSRAM IN C++
Z.I Punning fhe deveIopmenf environmenf b
Z.Z A simpIe C++ progrom b
Z.Z.I If you encounfer ony errors during buiIding b
Z.Z.Z 8reokdown of fhe progrom o
Z.3 Enfering dofo from fhe keyboord ond simpIe coIcuIofions 7
Z.4 Furfher reoding 9
3 DATA TYPES CONSTANTS AND VARIALES 10
3.I Infegers I0
3.Z FIoofing Poinf Mumbers I0
3.3 VoriobIes II
3.4 LiferoI Consfonfs IZ
3.b Consf IZ
3.o ExompIe - CoIcuIofing fhe oreo of o circIe IZ
3.7 Chorocfers I4
3.7.I ExompIe Ib
3.8 Sfrings Io
3.9 Objecf-orienfed progromming Io
3.9.I CIosses ond Objecfs Io
3.I0 Furfher reoding I7
4 CALCULATIONS AND OPERATORS 1
4.I Furfher reoding ZI
FUNCTIONS ZZ
b.I.I ExompIe: Funcfion wifh no orgumenfs Z3
b.I.Z ExompIe: Funcfion wifh orgumenfs Z4
b.I.3 ExompIe: Pefurning o voIue from o funcfion Zb
b.I.4 ExompIe: MuIfipIe orgumenfs Zo
b.I.b Ofher ExompIes Z7
b.I.o Funcfion Profofypes Z7
b.Z More obouf Argumenfs Z8
b.Z.I DefouIf orgumenfs 30
b.3 Sfofic objecfs 30
b.4 0IoboI objecfs 3Z
b.b Furfher reoding 3Z
USINS THE DEUSSER 33
7 ASSISNMENT 1 3
7.I 0effing if morked 37
Introduction to C++ Page 2
CONDITIONAL LOCkS: THE "IF" STATEMENT 3
8.I eIse 39
8.Z Mesfed bIocks 4Z
8.3 Common errors 4Z
8.4 Furfher reoding 44
9 REPEATED LOOPS: THE "WHILE" "DO ,,, WHILE" AND "FOR"
STATEMENTS 4
9.I whiIe 4b
9.Z do ... whiIe 4o
9.Z.I ExompIe 47
9.3 for 48
9.4 Mesfed Ioops 49
9.b breok b0
9.b.I ExompIe: ExponenfioI funcfion b0
9.o Infinife Ioops: oborfing your progrom bZ
9.7 Furfher reoding bZ
10 INPUT/OUTPUT 3
I0.I FiIe inpuf/oufpuf b4
I0.I.I ExompIe: Wrifing fo o fiIe bb
I0.Z Furfher reoding bo
11 ASSISNMENT Z - DRASSTER SIMULATION 7
II.I Firsf sfoge b7
II.Z Finishing fouches b8
II.3 Using your progrom b9
II.4 Submission b9
1Z ARRAYS 0
IZ.I One-dimensionoI Arroys o0
IZ.Z Possing orroys fo funcfions oI
IZ.Z.I ExompIe oI
IZ.3 MuIfi-dimensionoI orroys oZ
IZ.3.I ExompIe o3
IZ.3.Z ExompIe: reoding from o fiIe ob
IZ.4 Furfher reoding o7
13 ASSISNMENT 3
I3.I MumericoI infegrofion o8
I3.Z 0eor chonges o8
I3.3 CoIcuIofion of forque o9
I3.4 Adding 0rophics o9
I3.b 0effing if morked o9
14 FROM HERE,,, 70
1 ANSWERS TO SELECTED EXERCISES 71

Introduction to C++ Page 3
1 Introduction
There are many programming languages available and some of the most commonly
used are BASIC, FORTRAN, PASCAL, JAVA, C and C++. FORTRAN has been in
existence for many years and is widely used in scientific and engineering applications.
C and C++ are becoming very popular for all sorts of computing applications. In fact,
commercial applications such as Word and Excel, and even operating systems such as
Windows XP and Linux, were probably written in C++. Even the editor and compiler
that you use to create your C++ programs were themselves likely to have been written
in C++! Java is quite similar to C++ and is geared towards web applications.
Being able to use a programming language such as one of the above enables you to
harness the full programming capability of the computer. The principles that you will
be learning in this course can be used for development of a whole range of programs,
from knocking up simple tools for solving a particular problem, through to complete
simulation packages and applications.
1,1 About this course
This course is a basic introduction to the C++ language and is designed to get you up
and running quickly. However there is no substitute for sitting at a computer and
working your way through plenty of programs to learn a computer language. We
recommend that you try out most or all of the examples and exercises, many of which
can be downloaded from the web. Make use of your time effectively; don't sit there for
hours trying to work out why your program won't work. Get help from a member of
the teaching team who will be pleased to help you. There is a list of Frequently Asked
Questions (FAQs) on the web site.
These notes do not cover all the features of the language by any means. They just tell
you enough to do what you need to do in this course. Although it is not essential for
the course, the following book is recommended for further reading:
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag
Boxes like this contain asides. These contain more advanced or background
information and are not essential to the course.
Introduction to C++ Page 4
1,Z So whut is u progrumming Iunguuge?
Computers understand a language called machine code, which is just a series of
numbers. It is possible to program computers directly by entering machine code, and
in the very early days of computing this is exactly what was done. As you can
imagine, it was an extremely slow, tedious and error-prone task.
A programming language provides a description of the required task which is more
understandable to humans. To run the program, it first needs to be translated or
compiled into machine code which can be understood by the computer. It also needs to
be linked with other segments of machine code which are needed for it to run.
1,3 Progrum structure und pIunning
Some large programs, such as for fluid dynamics and structural modelling, air traffic
control, missile guidance, banking etc. can involve many tens or even hundreds of
person-years to develop by a team of programmers and may contain several million
lines of code. It is therefore essential that programs are developed in a consistent style
so that parts are easily understood. Large programs normally consist of a hierarchy of
small modules each of which can be tested separately. Object-oriented programming
is often used to help make such large programs manageable.
It is very easy to write unstructured, tortuous programs, but they can be very difficult
to understand and debug. In practice, the time spent writing a program in the first
place is usually a lot less than the time spent later testing, debugging and unravelling
it. It is worth spending a little more time at the outset in planning the structure. The
extra time spent when writing the program by breaking it down into bite-sized
functions, including useful comments and meaningful variable and function names,
can be saved many times over later on when it comes to trying to make the program
work properly.
How you develop your programs is up to you. Some people prefer to plan their
programs on paper using flowcharts before typing in the program code. Others write
the program out as 'pseudocode' a sort of shorthand version of the real code.
Whichever way you do it, it is important to plan things carefully or you can get into a
real mess.
1,4 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, Preface and Chapter 1
Introduction to C++ Page 5
Z Sturting to Progrum in C++
Z,1 Running the deveIopment environment
Most compilers include an Integrated Development Environment or IDE. Everything
can be done from within the IDE, including editing, compiling, linking, running and
debugging your program. Details of the compilers/IDEs available on the Departments
PCs and for home use are provided on the web site.
Z,Z A simpIe C++ progrum
Most programming books start with a program to write a simple message on the
screen - you cant get much simpler than that. So well do the same.
#include <iostream>

using namespace std;

// Program 2.1. A simple program to write a message to the screen

int main()
{
cout << "Hello mum" << endl;
return 0;
}
Exercise 2.1 Refer to the instructions on the web site to create a new program. Type in
the program above.
Dont worry if different bits of your program appear in different colours this is to
help you identify comments, keywords, variables and constants.
The program now needs to be built (compiled and linked) before it can be run. The
end result of compiling and linking is normally an executable or application file with
the extension .EXE. This is the machine-code version of the program that the
computer understands and can run.
After the program has finished running, its window should be closed.
Z,Z,1 If you encounter uny errors during buiIding
The compiler will list what the errors are and which lines they are on. In fact if you
click on the error message it should highlight that line for you (though sometimes the
wrong line will be highlighted). If you encounter a large number of errors dont panic
as they may all be caused by the same small mistake in your program. The most
common errors are:
missing out or using the wrong type of bracket or quotation mark
missing out a semi-colon.
Introduction to C++ Page 6
Check your program carefully against the listing above. Once the errors are corrected
try building and running again.
Z,Z,Z reukdown of the progrum
Ok, so what do the lines in this program mean? Well look at each line in turn, as all
later programs will contain similar statements, amongst others.
#include <iostream>
#include (and other commands starting with #) is called a preprocessor directive.
iostream is a header file which contains various definitions needed for the program
to be compiled. The #include directive simply treats the iostream file as if it
were inserted into your program at this point. Some header file names have a .h
extension; the newer convention is to have no extension, for example iostream.

using namespace std;
Dont worry too much about this one; just assume that you need it. It tells your
program that its allowed to use data and functions in the iostream header file
which are defined within the std namespace.

// Program 2.1. A simple program to write a message to the screen
Lines starting with // are comments and are purely for information - they are not
compiled and do not affect the operation of the program. However some comments are
usually essential for clarifying the program. The // symbols do not have to be at the
start of the line but can be after a program statement.

int main()
This is the start of the main function. Programs may be subdivided into many
functions, but all working programs must contain one and only one main function, as
this is the part of the program that is run first. Other functions may be called from the
main function (see section 9.5).
int means that the main function will return an integer value to the operating system
when the program finishes (see section 3.1). The parentheses () are always present
after a function name and may contain an argument list (section 5.2).

{
some program bits in here
}
These braces define a program block or segment. In this case the program segment is
the main function. It is normal to indent the block of statements within each set of
Introduction to C++ Page 7
braces by perhaps 4 spaces as this improves readability. Braces are often nested
inside each other.

cout << "Hello mum" << endl;
This displays the string Hello mum on the screen.
cout means standard output and is defined in iostream (see first line of
program). The standard output is normally the screen.
<< means send what follows to cout.
"" means that the contents Hello mum are a literal string.
<< endl means finish the line and move to the next one. A new line character is
sent to cout. Note that if endl was in quotes, i.e. "endl", the result
would be quite different as it would be treated as a literal string and the
word endl would be displayed on the screen instead. Try it if you like.
; denotes the end of the statement.

return 0;
This means return or exit from the program back to the operating system with a value
of zero. Sometimes other values are used to indicate that the program has finished
abnormally or with an error.
Exercise 2.2 Try changing the program to put a different message on the screen.
Z,3 Entering dutu from the keybourd und simpIe cuIcuIutions
Exercise 2.3 Type the following program in, save, compile, link and run it.
#include <iostream>

using namespace std;

/* Program 2.2. A simple program to read two values from the
keyboard and calculate their quotient. */

int main()
{
int first, second, quotient;

cout << "Please enter the first number: ";
cin >> first;

cout << "Now enter the second number: ";
cin >> second;

// calculate result and display on screen
quotient = first / second;

cout << "The result of " << first << " divided by " <<
second << " is " << quotient << endl;

return 0;
Introduction to C++ Page 8
}

It should give an output something like:
Please enter the first number: 128
Now enter the second number: 32
The result of 128 divided by 32 is 4

The numbers in bold are entered by the user.
The following new types of statement are used in this program.

/* Program 2.2. A simple program to read two values from the
keyboard and calculate their quotient. */
This is another form of comment. Everything between the /* and the */ symbols is
treated as a comment. Starting the two lines with // could equally well be used.

int first, second, quotient;
This defines integer variables called first and second.

cin >> first;
cin means standard input, and is normally the keyboard. cin is defined in the
iostream file.
>> means put the value from cin into variable first.

quotient = first / second;
This means "divide the contents of first by the contents of second and set the
contents of quotient equal to the result".

cout << " The result of " << first << " divided by " <<
second << " is " << quotient << endl;
This statement writes to the screen. However it is more complex than before and a
combination of literal strings and variables are written. The segment << first
means that the value contained in the variable first is written to the screen.

Exercise 2.4 What would happen if this part was changed from << first to
<< "first"?

Introduction to C++ Page 9

Exercise 2.5 Try the program for the two values 3 and 2. What value do you get?

The problem here is that first, second and quotient are defined as integers,
i.e. whole numbers. This means that they cannot contain fractional parts and the result
is rounded down to the next lower whole number.
One way to overcome this problem is to define the variables with type double
instead, i.e.
double first, second, quotient;

Exercise 2.6 Try modifying your program in this way and run it for the same two
numbers. We will look at what double means in the next section.
Z,4 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, Chapter 2

Introduction to C++ Page 10
3 Dutu Types Constunts und VuriubIes
Any variable and constant in a C++ program has a type which defines how much
storage space it needs and its precision and range.
C++ contains a number of inbuilt fundamental data types and perhaps the key
difference is between integers and floating point types.
3,1 Integers
Integers are whole numbers. The complete theoretical set of integers ranges from
to +. However the range of values that an integer can take in a computer is limited
by how much memory space is allocated for it.
Aside: The fundamental unit of data in a computer is a bit or one binary digit. A bit
can take the values 0 or 1. Memory in a computer is arranged in groups of 8 bits. An
8-bit group is called a byte.

C++ contains a number of different integer types. Probably the most common are
char and int.
Type Storage space Range
char
1byte / 8 bits -128 to 127
short
2 bytes / 16 bits -32768 to 32767
int (also called long) 4 bytes / 32 bits

-2147483648 to
2147483647
The char type will be described in section 3.7.
3,Z FIouting Point Numbers
Unlike integers, floating point or real numbers need not be whole numbers but can
have decimal fractions (e.g. 1.234) and exponents (e.g. 0.123410
-5
). The two main
floating point data types in C++ are float and double (meaning double precision).
In most cases double is the preferred floating point type.
Introduction to C++ Page 11

Type Storage space Range Precision
float
4 bytes approx. 110
-38
to 310
+38
6 digits
double
8 bytes approx. 210
-308
to 210
+308
15 digits

Floating point numbers can be used for extremely small or extremely large numbers.
The downside is that round-off error occurs in floating point calculations, which can
cause inaccuracies and other problems.
In contrast, integer calculations such as addition, subtraction and multiplication are
exact, provided that the result is within the range of that integer type. Integer division
may not be exact as any fractional part (or remainder) is lost.
For these and other reasons, it is always important to take care that a suitable data type
is used for a particular situation.
3,3 VuriubIes
A variable can be thought of as a data store which for convenience is given a name.
The data can be accessed and changed by referring to the name.
The name of a variable can contain upper or lower case alphabetical characters,
numbers and the underscore character _. No other characters are allowed. It must start
with an alphabetical character. The language is case sensitive, that is, a1 and A1 are
different variables.
Unlike some languages such as Basic or Fortran, all variables have to be defined
before they can be used. This specifies the type of the data and allocates an area in
memory to contain the data. It is done using statements such as the following.
char Number; // defines Number as a variable
// of type char.

int PartCount, Item_Cost; // defines PartCount and Item_Cost
// as variables of type int.

double Temperature = 32.7; // defines Temperature as a variable
// of type double, and initialises it
//(sets its initial value).

float x = 2 * Temperature; // defines x as a variable of type
// float, and initialises it to
// 2Temperature, where Temperature
// was defined and initialised above.

Introduction to C++ Page 12
3,4 LiteruI Constunts
Data can be expressed in a program directly as numerical values or literal constants.
e.g. 23 - integer
'A' - char
3.14159 - double
-0.12345e-5 - double (e-5 means 10
-5
)
2.3456f - float
0xF6 - integer (0x means hexadecimal, i.e. base 16)
If the literal constant contains a decimal point or an exponent (denoted by an e or E,
e.g. 12e-4) then it is double, otherwise it is integer.
3, Const
In many situations it is better to assign a name to a constant than to use a literal
constant. There may be a number of reasons for this.
A name may be more meaningful than a number.
If the same value is used several times in a program, it is simpler to change the
value in the declaration than to change every occurrence of the number in the
program, and it reduces the chances of mistakes.
Whilst variables can be used for this purpose, it is better to use the const keyword to
prevent the value of the variable from being inadvertently changed. For example:
const double PI = 3.1415926;
const int MAX_CLASS_SIZE = 120;
const char NEW_LINE = '\n';

const float Length = 100.0;
const float Area = Length * Length;

const double x; //WRONG: x must be initialised

3, EumpIe - CuIcuIuting the ureu of u circIe
This program and the later example programs are available for downloading from the
course website. Download it and open it in the C++ editor.
Introduction to C++ Page 13

#include <iostream>
using namespace std;

// Program 3.1. A simple program to calculate the area of a circle.

int main()
{
double Diameter;
const double Pi = 3.1415926;

cout << "Please enter the diameter in m: ";
cin >> Diameter;

// calculate result and display on screen
double Area = Pi * Diameter * Diameter / 4.0;

cout << "The area of a circle of diameter " << Diameter
<< " is " << Area << " m^2" << endl;

return 0;
}

Exercise 3.1 Modify the program to calculate the surface area of a cylinder (including the
two ends) given a length and diameter. The program output should look
something like this:

Please enter the diameter in m: 0.8
Now enter the length in m: 1.2

The surface area of a cylinder of diameter 0.8 m and length 1.2 m
is 4.02124 m^2


Exercise 3.2 Write a program to calculate the roots of a quadratic equation:
ax bx c
2
0 + + =

where the solutions are given by
x
b b ac
a
=

2
4
2

Your program should give an output of the form
Please enter the coefficients a, b and c: 1 1 -6

The roots are 2 and -3


Introduction to C++ Page 14
You can enter three values on the same line using a statement like the following:
cin >> a >> b >> c;

The sqrt function can be used to find the square root, e.g.
Root1 = (- b + sqrt(b * b - 4.0 * a * c)) / (2 * a);

sqrt is declared in the math.h header file, so you need the following line at the
start of your program:
#include <math.h>


Note: this program will only work if 0 4
2
ac b . Try it for coefficients of:
1 1 -6
1 9 -10
25 10 1
1 1 1 (this should give an error).
Later you will modify the program to deal with 0 4
2
< ac b .
3,7 Churucters
Alphabetical (a, B, etc.), numerical (1, 2, etc.) and other (!, # etc) keyboard characters
are stored in PCs and most other types of computer using a numerical code called
ASCII code (American Standard Code for Information Interchange). Whilst the char
type can be used to store numbers, it is usually used to store the ASCII code for a
character.

Introduction to C++ Page 15
3,7,1 EumpIe
#include <iostream>
using namespace std;

// Program 3.2. A simple program to return the ASCII code
// of a character

int main()
{
char Character;
cout << "Please enter the character: ";
cin >> Character;

// Write Character to screen both as a character (default)
// and as its ASCII code (by converting to an integer)

cout << "The character " << Character <<
" is stored in memory using the ASCII code" <<
int(Character) << endl;

return 0;
}
Exercise 3.3 Download the above program from the web (see section 3.6). Use it to find
the ASCII codes for the digits 0, 1 and 2 and the letters a, b, A and B.

Literal constants for characters are denoted by single quotes ('), for example 'x'.
Some special characters cannot be entered directly, perhaps because they are not
available from the keyboard or are reserved for special purposes. They are denoted by
escape sequences, starting with a backslash (\). Some useful ones are:
new line \n single quote \' tab \t
backslash \\ double quote \"
For example, the literal character constant '\'' contains a single quote character.

Exercise 3.4 What output does the following produce on the screen?
(answer at end of booklet)
cout << "\"hello\"\n\'\\\'";
Introduction to C++ Page 16
3, Strings
A string is a sequence of characters. In C++ a string can be stored as an array of
characters. We will not be looking at arrays in general until chapter 12, but strings are
so widely used that we shall introduce them here.
Perhaps without realising it you have already used string constants in the programs so
far. String literal constants are enclosed in double quotes, for example
"Hello there"
The string is stored as a sequence of ASCII codes representing the characters. In
addition, a code of zero (not to be confused with the code for the character '0') is
automatically added to the end to tell the computer where the string ends.
String variables can be defined using the following:
char String1[] = "Hello there";
This defines a character array with just enough space to store the string "Hello there"
(including the zero character at the end).

char String2[20];
This defines a character array with space for 20 characters.

char String3[20] = "Hello there";
This defines a character array with space for 20 characters, and initialises the first 12
characters with "Hello there" followed by a zero character.
3,9 Obgect-oriented progrumming
C++ is an object-oriented language. It is possible to group sets of related variables,
constants and functions together into classes. Classes can be created for representing
distinct entities such as matrices, people, graphics and so on. The class contains the
data and functionality for that entity.
Object-oriented programming is an extremely powerful modern technique, and is great
for large applications which may contain many hundreds or thousands of variables and
functions.
3,9,1 CIusses und Obgects
A class is essentially a compound variable type composed of a collection of members,
which can be variables, constants and functions. An object is an instance of a class.
What does this mean? Consider the following:
Introduction to C++ Page 17
class vector
{
public:
double GetModulus();
private:
double x, y, z;
};

double vector::GetModulus()
{
return sqrt(x * x + y * y + z * z);
}
This declares a simple class called vector which contains member variables x, y and
z representing the coordinates, and a member function GetModulus for calculating its
argument. Don't worry about the details of how this is done. The variables x, y and z
are private and are invisible to the user.

vector A(15.2, -5.6, 13.3);
vector B = A + vector(1.0, 2.0, 3.0);
This defines A and B as objects of class vector. Members of the classes can be
accessed using the 'dot' operator:
cout << "Modulus of A is " << A.GetModulus();

A slightly more sophisticated version of this is on the website.
Classes are a key part of the C++ language. One advantage of a class is that it is a self-
contained representation of something, so that once a class has been created it may be
suitable for re-use in several applications. Classes can be derived from other classes.
There are libraries of classes available for doing common things such as graphics,
Windows programming, vector and matrix algebra etc.
Creating classes is an advanced topic. However, it is common to use classes created by
others, and many classes are pre-defined in the standard C++ library. This can
simplify our programming as we do not need to worry too much about how the class
works - we just need to know what it does and how to interface with it. You have
already used classes for input and output in this course; cin and cout are pre-
defined class objects of class type ifstream and ofstream respectively. You do
not need to know about the innards of these classes, you just need to know how to use
them.
3,10 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, Sections 2.5, 3.1, 3.2, 3.5, Chapter 8
Introduction to C++ Page 18
4 CuIcuIutions und Operutors
key points
All variables and constants have a definite type.
The int type is usually used for whole numbers in a limited range, for example if
you are counting something.
The double type is usually used for numbers which are not whole or have large
exponents, for example a length or temperature.
The char type is used for characters which are stored in ASCII code. Character
constants are denoted by '.
Strings are stored as arrays of characters terminated by a zero code. String
constants are denoted by ".
If you divide one integer by another you may get an unexpected result.
Floating point numbers may suffer from round-off error.
Variables can be turned into constants using the const keyword.
Classes are groups of variables, constants and functions for representing specific
entities or concepts.

You have already met the operators +, -, *, /, =, << and >>. There are many others in
the C++ language, some rather obscure. They have strict rules of precedence which
usually match what would be expected. For example, * and / take precedence over +
and -, which take precedence over the assignment operator =.
Note that = does not really mean 'equals'. It actually means put the value of the
expression on the right-hand side into the variable on the left-hand side. This means
that statements such as the following are valid.
x = x + 10;
Obviously x cannot equal x+10! What this statement actually does is to increase the
value contained in variable x by 10.
Statements like the following are not valid.
10 = i;
x + y = a + b;
You cannot assign a value to 10, as it is a constant and cannot be changed! Nor can
you assign a value to x + y, as it is an expression and not a single variable.

Introduction to C++ Page 19
Exercise 4.1 Try the following. (Note: this is not a complete program. The complete
program is available on the web.)
int x, a = 12, b = 3, c = 2;

x = a + b * c; // means calculate a + (b * c), assign the result to x.
cout << x << endl;

cout << " a / b * c = " << a / b * c << endl;
// means calculate (a / b) * c, i.e. (a * c) / b), not a / (b * c)

cout << " a / b / c = " << a / b / c << endl;
// means calculate (a / b) / c which is equivalent to a / (b * c)

The precedence can be controlled using parentheses, for example
x = (a + b) * c;

y = a / (b * c);


Some other useful operators are the following:
++ Increment the value of the variable by one
-- Decrement the value of the variable by one
These can appear before or after the variable (the difference need not concern us here).
i++; // equivalent to i = i + 1;

C++; // equivalent to C = C + 1
//(this is how the language got its name -
// it was developed from the older C language)

--j;

+= Add the right-hand side to the left-hand side and assign the result to the left-
hand side.
-= Subtract the right-hand side from the left-hand side.
*= Multiply the right-hand side by the left-hand side.
/= Divide the right-hand side by the left-hand side.
e.g.
i += j; //equivalent to i = i + j

j -= 1; //equivalent to j-- or j = j - 1;

k *= k; // equivalent to k = k * k;

Other operators will be introduced later in the course.
Introduction to C++ Page 20
You can mix variable types in a single expression. For example, the following are
valid.
int i = 2;

double x = 3.5;

double z = i * x;

int j = x / i; // the result will be rounded down to the
// nearest integer.

When an arithmetic operation is performed with mixed types, one value is converted
automatically to the other type. Where integers and floating point types are involved,
the integer gets converted to the floating point type.
Care should be taken when part of an expression involves integer division, for
example
double x = 1.38 * (3 / 4);

int i = 3, j = 4;
double y = 1.38 * (i / j);


Here the part in parentheses is evaluated first and, as it is an integer (sub-)expression,
its result is rounded down to zero. This is a very common error.
This problem can be avoided by forcing literal constants to be type double by adding a
decimal point, or by casting variables or expressions. Casting is done by inserting the
name of the required type before the value to be converted, which should be in
parentheses. For example:
double x = 1.38 * (3.0 / 4.0);

int i = 3, j = 4;
double y = 1.38 * double(i) / double(j);

Introduction to C++ Page 21

Exercise 4.2 Try the following. Which give the correct result, and why?
(answer at end of booklet)
cout << 3.0 * 2.0 / 4.0 << endl;
cout << 3 * 2 / 4 << endl;
cout << 3.0 * (2 / 4) << endl;
cout << 3 * (2.0 / 4) << endl;
cout << (3 * 2.0) / 4 << endl;
4,1 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, sections 3.1-3.4
Introduction to C++ Page 22
Functions
key points
A function should perform a clear-cut task.
Use functions to simplify your main program and to avoid repeating similar pieces
of code.
Avoid using the same names for functions and variables.
To call a function you must have brackets after the function name.
Values are passed to a function through the argument list, in brackets.
A value is returned from a function by the return statement.
The values of variables passed as arguments to the function cannot normally be
changed by the function unless they are passed by reference.
The number of arguments when calling the function should be the same as in the
function header, unless there are default arguments.
Variables are destroyed on leaving a function, unless they are defined as static.
If objects are defined in a function they are local. If they are defined outside of any
function they are global.

Almost all but the smallest of programs use functions in order to break the program up
into modules of manageable size. This makes the program easier to understand. It also
enables you to call the same function from several places within a program, avoiding
the need to repeat the same code several times.
You have already called some pre-defined functions, for example the sqrt function
for calculating the square root of a number. You will write some functions yourself as
part of your programs, but a large number of standard functions are already written
and compiled for you in the C++ libraries.
Functions normally are self-contained and have their own distinct sets of variables that
are totally separate from those in the main program. Values can be passed to the
function via the argument list (section 5.2), and the result of the function can be
passed back via the return value.
Give some thought as to what you want your functions to do. Normally a function
performs a clear-cut task. It is possible to create functions willy-nilly for the most
basic of tasks and this can be very inefficient.
Introduction to C++ Page 23
Use of functions is a very important part of programming and it may take some time to
grasp the use of arguments and return values. Take your time in going through this
chapter and make sure that you understand how functions are called and data are
passed to and from functions.
,1,1 EumpIe: Function with no urguments
Here's an example of a very simple function that just displays a message on the screen.
//Program 5.1. Example of a simple function with no arguments

#include <iostream>
using namespace std;

void Message()
{
cout << "This is a message" << endl;
}

int main()
{
Message();
return 0;
}

The key parts of this program are:
void Message()
{
cout << "This is a message" << endl;
}
This is the function called Message. The function starts with a function header
defining its return type, name and argument list. The function header is the same as or
very similar to the function prototype but without the semi-colon at the end.
The function itself is a block of statements within braces { ... }.

Message();
This calls the function. The execution of the program jumps from this line to the start
of the function. The parentheses must always be present when calling a function, even
if they are empty.
When you run your program, the main() function is executed automatically. Other
functions are not executed unless they are called explicitly like the above.
Avoid using the same names for functions and for variables, as this causes confusion
and problems. For example, in the following, Tension is both a function and a
variable.
Introduction to C++ Page 24

void Tension()
{
double Tension = ;
}

,1,Z EumpIe: Function with urguments
The above function is very limited as no data is passed between the main function and
the Message function. Here is a simple function to demonstrate how to pass a data
value to it. The function displays on the screen the square of an integer that is passed
to it.

//Program 5.2. Example of a simple function with data passed
// to it as an argument

#include <iostream>
using namespace std;

void ShowSquare(int x)
{
int y = x * x;

cout << "The square of " << x << " is " << y << endl;
}

int main()
{
int Number;

cout << "Enter a number: ";
cin >> Number;

ShowSquare(Number);
return 0;
}

The key parts are:
void ShowSquare(int x)
This function header states that it has one argument named x of type int.

ShowSquare(Number);
This line calls the function with Number as its argument. The value of Number is
copied into x in the function.
The variables defined in one function are not accessible to the other function. For
example, the following function is invalid because Number is not directly accessible
to the ShowSquare function.
void ShowSquare()
{
Introduction to C++ Page 25
int y = Number * Number;

cout << "The square of " << Number << " is " << y << endl;
}
Arguments provide a convenient means of passing data to the function.
,1,3 EumpIe: Returning u vuIue from u function
A data value is passed to the above function via the argument list, but it is still limited
as no value is passed back from the function. This can be achieved using the return
statement. Here is an example.

//Program 5.3. Example of a simple function that returns a value

#include <iostream>
using namespace std;

int Square(int x)
{
int y = x * x;

return y;
}

int main()
{
int Number, SquareOfNumber;

cout << "Enter a number: ";
cin >> Number;

SquareOfNumber = Square(Number);

cout << "The square of " << Number << " is "
<< SquareOfNumber << endl;

return 0;
}


The key parts now are:
int Square(int x)
The int on the left-hand side of the function header specifies that the function returns
an integer value.
return y;
The return statement does two things: it transfers control back to the function that
called it, and it specifies the value (in this case the contents of variable y) to be
returned to the function that called it.
SquareOfNumber = Square(Number);
This calls the function, putting the value returned by the function into the variable
SquareOfNumber.
Introduction to C++ Page 26
When calling a function the argument(s) do not have to be variables and can be
constants or more complex expressions. Here is an example of a call to the same
function in which the argument is itself a function call.
cout << Number << " to the power 4 is " <<
Square( Square(Number) ) << endl;
What is happening here? First the Square function (in the parentheses) is called with
Number as its argument. The result of the Square function becomes the argument
when Square is called a second time. The result of this is then displayed using
cout. It is equivalent to writing (n
2
)
2
.
Exercise 5.1 Put the above statement into program 5.3. Now modify this statement to
calculate the eighth power of the number using the Square function. Why
does this not give the correct result for large numbers?
(answer at end of booklet)
,1,4 EumpIe: MuItipIe urguments
An example of a function to calculate the length of the hypotenuse of a triangle, and a
main program that calls it, is given below.
//Program 5.4. To calculate the length of the hypotenuse of a
//right-angled triangle, given the lengths of the other
//two sides.

#include <iostream>
#include <math.h>
using namespace std;

double Hypotenuse(double x, double y)
{
return sqrt(x * x + y * y);
}

int main(void)
{
double Side1, Side2, Side3;
cout << "Enter length of first and second sides: ";
cin >> Side1 >> Side2;

Side3 = Hypotenuse (Side1, Side2);
cout << "The length of the hypotenuse is " << Side3 << endl;

return 0;
}
The key parts of this program are:
double Hypotenuse(double x, double y)
{
return sqrt(x * x + y * y);
}
The function has two arguments (in parentheses) both of type double, and returns a
value of type double.
The function calls the standard library function sqrt (which is declared, i.e. has a
prototype, in math.h), and returns the result.
Introduction to C++ Page 27

Side3 = Hypotenuse (Side1, Side2);
This calls the function, sending two arguments of type double to it. x takes the value
of Side1, and y takes the value of Side2. The function returns a value of type
double, which is stored in Side3.
This and the following line could be condensed into one statement, avoiding the need
for the variable Side3:
cout << "The length of the hypotenuse is " <<
Hypotenuse (Side1, Side2) << endl;
Exercise 5.2 Download and run this program. Modify it to calculate the length of a vector
in three dimensions, i.e.
2 2 2
z y x Length + + = . Try this for (x, y, z) = (1,
2, 2).

,1, Other EumpIes
Examples of function headers are:
int main (void)
or
int main ()
This is a special function (which must be present in any program) which has no
arguments (void) or () and which returns a value of type int.

void DisplayValue (char Text[], double Value)
This function has two arguments of type char[] (i.e. a string) and double. The
function does not return a value.

double Argument (double x, double y)
This has two arguments of type double, and returns a value of type double.
Valid calls to the above functions might be:
DisplayValue("Maximum pressure", PMax*1.e-5);

cout << Argument (L_Horiz, L_Vert);

z = Argument (1.2 * x * sin (theta), 2.3 * x * cos (theta));

,1, Function Prototypes
In all of the above programs, the functions were defined above the line where they
were called. This means that the compiler knows what to do when it reaches the line
Introduction to C++ Page 28
containing the function call. However sometimes a function is defined below the
line(s) where it is called, or even in a different file altogether. It is then necessary to
use a function prototype to declare the number and type of arguments and the type of
the return value. For example:

//Program 5.5. Example of a function prototype

#include <iostream>
using namespace std;

int Square(int x); //FUNCTION PROTOTYPE

int main()
{
int Number;

cout << "Enter a number: ";
cin >> Number;

cout << "The square of " << Number << " is "
<< Square(Number)<< endl;

return 0;
}

int Square(int x)
{
return (x * x);
}
The function prototype is the same as the function header but with a semi-colon at the
end. The names (but not the types) of the arguments can be omitted if required. For
example, both of these are valid prototypes:
int Square(int x);
int Square(int);

Function prototypes are usually defined in header files. For example, math.h (see
program 5.4) contains the prototype for the sqrt function, amongst many others.
,Z More ubout Arguments
The arguments in the statement that calls the function are sometimes called actual
arguments. The arguments in the function header and prototype are called formal
arguments.
By default, arguments to functions are passed by value. That is, only a copy of the
value is passed to the function and not the variable itself. This means that the values of
any variables in the actual argument list when the function is called cannot be changed
by the function itself.
There are exceptions to this, and it is possible to pass arguments by reference. This
means that the function is told the location or address of the variable in the actual
Introduction to C++ Page 29
argument list. The function is then able to change the value of that variable. Variables
can be passed by reference by using the & operator in the function header and
prototype. For example:
double Hypotenuse (double &x, double &y)

The function is called in exactly the same way as before, and in this case would have
exactly the same effect.
One circumstance where it is useful to pass by reference is where a function needs to
return more than one value. For example, here's a function to swap two numbers.
//Program 5.6. A function to swap two numbers of type double.

void Swap(double &x, double &y)
{
double temp = x;
x = y;
y = temp;
}

Exercise 5.3 Write a main program to enter two values from the keyboard into two
double variables, call the above function to swap them round and then
display the new values of the variables.
(answer on website)
Introduction to C++ Page 30

Exercise 5.4 Why do you need the temp variable here? What would happen if it was
changed to the following? (try it!)
(answer at end of booklet)
{
x = y;
y = x;
}

In fact, strings are passed by reference. It is more efficient to tell the function the
address of the start of the string than to copy the whole string, especially as the string
can be extremely long. The same applies to arrays (section 12.2).
To ensure that a function cannot change the values in a string or array, the const
keyword can be used in the function header and prototype:
int DisplayString (const char text[]);

,Z,1 DefuuIt urguments
Normally a function should be called with the same number of arguments that it is
defined with. However it is possible to leave the last argument(s) out if they are
declared as default arguments in the function prototype or header. For example:
int GetValue (const char Text[], int MinVal = 0, int MaxVal = 100)
The equals signs specify the default values.
The following statements are valid for calling this function:
i = GetValue("Number of Items", 1, 20);

i = GetValue("Number of Items", 1); // MaxVal will take the default

i = GetValue("Number of Items");

Note that the list of default arguments, if any, must start at the end of the argument
list. The following are wrong:
int GetValue (const char Text[], int MinVal = 0, int MaxVal)

int GetValue (int MinVal = 0, int MaxVal = 100, const char Text[])

,3 Stutic obgects
So far, all objects (variables and constants) have been defined within the body of a
function. Those objects are only known to that function. They are created each time
Introduction to C++ Page 31
the function is entered, and cease to exist when that function terminates. They have
local scope and are often known as automatic objects, as they are created and
destroyed automatically on entering and leaving the function.
It is possible to define objects that retain their values for the lifetime of the program.
For example, here's a program to calculate the running average of a series of numbers.
The main program here is trivial but it illustrates the principle.
//Program 5.7. To calculate the mean of a series of numbers.

#include <iostream>
using namespace std;

//This function calculates and stores the sum of a series of numbers,
//and the number of numbers, and returns the mean.

double UpdateMean (double NewValue)
{
static double Sum = 0.0;
static int Count = 0;

Sum += NewValue;

Count++;

//Enable the next lines (remove the //) if you want to
//see what's happening inside the function

// cout << "Sum = " << Sum << " Count = " << Count <<
// " NewValue = " << NewValue << endl;

return (Sum / Count);
}
int main(void)
{
cout << UpdateMean (3.2) << endl;
cout << UpdateMean (4.5) << endl;
cout << UpdateMean (2.3) << endl;
cout << UpdateMean (1.2) << endl;
return 0;
}

Here Sum and Count are defined as static variables and initialised to zero. Static
objects exist for the lifetime of the program.

Exercise 5.5 Download this program and try it. Try omitting the static keywords from
the function. The program will not work as the variables Sum and Count
are re-created and reset to zero each time the function was entered, and
destroyed on leaving the function.

Note that the variables are initialised the first time that the function is called and not
every time. The statement
static int Count = 0;
is quite different to the statements
Introduction to C++ Page 32
static int Count;
Count = 0;
where Count is reset to zero every time the function is called. The program wouldnt
work correctly.
,4 SIobuI obgects
So far our variables and constants have been defined with local scope so that they are
only accessible to that particular function. However we often want the same value to
be available to several functions or the whole program. An object can be defined with
global scope by declaring it outside of any function. It is then accessible to any
function following it in that file. Such an object will be static by default. This is often
easier and more efficient than passing it from function to function via argument lists.
It is best to use the const keyword with global objects wherever possible. Global
variables should be used with caution or avoided as any function in that file can
change their values, which may cause errors that can be difficult to track down.
e.g.
#include <iostream>
using namespace std;

static const double GRAVITY = 9.81; //static can be omitted

const double PI = 3.1415926;

const int MAX_LENGTH = 30;

const char VERSION[MAX_LENGTH] = "Version number 3.21";

int main(void) //start of main function
{
... etc.
, Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, chapter 5
Introduction to C++ Page 33
Using the Debugger
key points
You can debug your program by writing to the screen but it is easier and more
powerful to use the debugger.
The debugger enables you to stop the program at a particular line using a
Breakpoint, check the value of a variable or expression using Inspect, and step
through the program line by line.
More often than not, your program will not work properly first time and you will need
to spend some time debugging it. Even if it does appear to work, it is often worth
delving into the operation of the program just to make sure.
One way to debug your program is to modify it temporarily to write to the screen. You
can display the values of variables, or simply put messages to tell you where the
program has reached. This has been done in program 5.7 (here the message has been
disabled or commented out using the // symbols).
//Enable the next lines (remove the //) if you want to
//see what's happening inside the function

// cout << "Sum = " << Sum << " Count = " << Count <<
// " NewValue = " << NewValue << endl;

return Sum / Count;

Exercise 6.1 Load this program and enable these two lines by removing the // symbols.
Run the program and examine its behaviour.
This technique is effective, but does mean that the program has to be modified then re-
compiled and linked after the messages have been put in. It can also mess up the
normal screen output from the program.
An alternative and more powerful method is to use the inbuilt debugger. This enables
you to stop the program at any line, step through line by line, and examine and change
the values of variables. Instructions for using the debuggers for the recommended
compilers are given on the web site.
Introduction to C++ Page 34

Exercise 6.2 Load the above program again, with the message in the function disabled.
Investigate the use of the debugger as follows.
Because of a bug in Visual Studio version 6.0, the debugger does not work with local
static variables. To avoid this, move the following lines to before the start of the
UpdateMean function so that they are global:
static double Sum = 0.0;
static int Count = 0;
Put a breakpoint on the following line:
Sum += NewValue;
Run the program. Inspect the value of Sum. A window is created showing the value
and some other information about the variable. You can leave this window open.
Step to the next line and notice how Sum has changed.
Click the Run button again to continue the program.
There are other useful tools in the debug menu; feel free to try them out.
Introduction to C++ Page 35
7 Assignment 1
This is the first stage of constructing a program for simulating a car driving along a
road. Eventually you will end up with a program in which you can 'drive' the car using
the keyboard for the accelerator and brake, and the driver's view will be displayed on
the screen (you will be given the graphics functions to do this).
The objective of assignment 1 is just to calculate the acceleration at a given instant.
The user should enter the road speed, followed by the throttle setting as an integer
from 0 to 9 (9 being maximum throttle). The program should then display the results
on the screen. For the time being only 5th gear will be used.
Newton's second law gives the equation of motion
( ) F TR a JR M = +
2
(7.1)
where the meanings of these symbols (and others we'll need below), and their units
and values where available are:
a Acceleration m/s
2
A Frontal area of vehicle 1.97 m
2
C
D
Drag coefficient 0.34
C
R
Coefficient of rolling resistance 0.025
F Total drag force N
g Gravitational acceleration 9.81 m/s
2

J Moment of inertia of engine 0.28 kgm
2
K Brake coefficient 1000N
M Mass of vehicle 1350.0 kg
R Ratio of engine speed to vehicle speed 10.75 rad/m (5th gear only)
T Torque from engine Nm
Brake setting (0 to 9) 0
Transmission efficiency 0.95
Throttle setting (0 to 9)
Air density 1.2 kg/m
3

Engine speed rad/s
The engine is a 1.8L petrol engine. Experimental measurements of torque against
speed at minimum and maximum throttle are shown in figure 7.1. Later we will be
using these data points directly but for now we will approximate the torque using the
equations
d c b T + + =
2
(7.2)
where
Introduction to C++ Page 36
21 . 8 33 . 9
10 47 . 8 10 06 . 4
10 66 . 3
2 2
5
+ =
=
=

d
c
b
(7.3)

Figure 7.1 Measured torque for minimum and maximum throttle,
and approximated torque curves for throttle settings of 0 to 9

The drag force is made up of tyre rolling resistance, aerodynamic drag ('wind
resistance') and the braking force. It is given by the equation
F C Mg C AV K
R D
= + +
1
2
2

(7.4)
Write a function to calculate engine torque for a given engine speed and throttle
setting, using equations 7.2 and 7.3. This function should have a header similar to the
following.
double EngineTorque(double EngineSpeed, int Throttle)
Notice how using this function modularises the program. The engine calculations are
encapsulated inside this function, which can be written and tested separately from the
rest of the program.
Note also how, although single letters are used for the algebraic symbols in equations
7.1 to 7.4, it is often clearer to use longer, meaningful variable names in your
programs.

-100
0
100
200
0 100 200 300 400 500 600 700
Engine speed (rad/s)
T
o
r
q
u
e

(
N
m
)
Min throttle
Max throttle
Introduction to C++ Page 37
Write another function to calculate the drag force for a given road speed and brake
setting, using equation 7.4. This should have a header similar to the following.
double Drag(double RoadSpeed, int Brake)

Write a main program to do the following.
1. Read values of road speed and throttle setting from the keyboard.
2. Calculate acceleration for a brake setting of zero. The functions for torque and
drag can be called from within the formula for acceleration.
3. Display the acceleration on the screen. The output should look something like this:
Enter the road speed (m/s): 30
Enter the throttle setting: 9

At a speed of 30 m/s and throttle setting of 9
the acceleration is 0.596221 m/s^2.
You can use the above numbers as a check of your program.
Use the const keyword wherever possible for fixed values such as the mass of the
car. Take care to decide whether they should have local scope (defined within a
function and available only to that function) or global scope (defined outside of the
functions and available to all functions) (see section 5.4).
7,1 Setting it murked
Once your program is finished, save it using your username as the file name (e.g.
en0xyz.cpp), attach it to an email and send to the instructor.
Before you do so it is worthwhile to go back through your program tidying and
checking it. Make sure that:
the program works properly and does what is asked!
the program is logically structured;
sufficient comments are included to clarify how it works (don't go overboard with
comments - just add enough to explain what's going on);
sensible variable and function names are used;
the program blocks are indented correctly.
Please note the Department's guidelines regarding plagiarism. The Department has
software that compares every submitted program to check for signs of plagiarism. If a
program has obviously been copied no mark will be given, and in the case of joint
efforts marks will be divided accordingly.
Introduction to C++ Page 38
ConditionuI bIocks: the "if" stutement
key points
if and else can be used for directing the flow of the program to different blocks
depending on a logical condition.
The logical condition is an integer value. False is zero, true is normally 1.
Several if ... else statements can be combined to give an
if ... else if ... else structure.
if and else blocks can be nested.
Remember to use ==, not = in a condition expression.
Do not terminate an if statement with a semicolon.
A condition such as (0 < x < 2) is probably wrong and should be
(0 < x && x < 2).

A function normally runs though each line until it gets to the end. However it is almost
always necessary to control the program flow in some way, such as:
choose which bits of program to execute depending on a logical condition;
repeat bits of program several times.
The first of these is done using the "if" statement.
if (condition)
statement or block of statements in { }


Condition is usually a logical expression. If the logical expression is true, the
following statement or block of statements is executed, otherwise the program skips to
the next statement.
The logical operators are:
==
is equal to
!=
is not equal to
<
is less than
>
is greater than
<=
is less than or equal to
>=
is greater than or equal to
&&
and
||
or
!
not

Introduction to C++ Page 39
e.g.
if (i == 0)
cout << "i is zero" << endl;

if (j >= 0 && j <= 10)
cout << "j has a value of between 0 and 10 inclusive" << endl;

if (Key == 'y' || Key == 'Y') //y or Y pressed?
cout << "You pressed the letter y" << endl;

if (Key != 'q' && Key != 'Q') q not pressed AND Q not pressed?
cout << "You did not press the q key" << endl;

In fact, in C++ a logical expression is actually a numerical expression, where 0 is false
and any other integer is true. Thus the following statements are valid:
int x, y;

cout << "Enter x and y: ";
cin >> x >> y;

if (x)
cout << "x is non-zero" << endl;

if (!y)
cout << "y is zero" << endl;

int check = (x == y); //variable check takes the logical value of
//the result of comparing x with y. If x==y,
//check = 1, else check = 0.
if (check)
cout << "x and y are equal" << endl;


,1 eIse
The optional else statement can also be used so that a statement or block of
statements is executed if the condition is false:
if (condition)
statement or block of statements
else
statement or block of statements

e.g.
if (i > 0)
cout << "i is positive" << endl;
else
cout << "i is negative or zero" << endl;

More than one if ... else block can be combined to create an
if ... else if ... else structure, for example:
Introduction to C++ Page 40
if (i > 0)
cout << "i is positive" << endl;

else if (i == 0)
cout << "i is zero" << endl;

else
cout << "i is negative" << endl;

It is normal to indent the conditional statements as this aids readability.
If more than one statement needs to be conditional, they need to be in a block
surrounded by braces, for example
if (i > 0)
{
j = i * i;
cout << "i is positive" << endl;
}
else if (i == 0)
{
j = 0;
cout << "i is zero" << endl;
}
else
{
j = -i * i;
cout << "i is negative" << endl;
}

Exercise 8.1 Download and run the following program for comparing the ages of two
people. Modify it to use else if and else blocks.
(answer at end of booklet)
#include <iostream>
using namespace std;

// Program 8.1. To compare the ages of two people

int main(void)
{
const int MAXLENGTH = 20;

char name1[MAXLENGTH], name2[MAXLENGTH];
int age1, age2;

//note the use of the getline function for reading strings
cout << "Enter the first name :";
cin.getline(name1, MAXLENGTH);

cout << "Enter the second name :";
cin.getline(name2, MAXLENGTH);

cout << "enter the age of " << name1 << ":";
cin >> age1;

cout << "enter the age of " << name2 << ":";
cin >> age2;

if (age2 > age1)
{
cout << name2 << " is older than " << name1 << endl;
Introduction to C++ Page 41
}

if (age2 < age1)
{
cout << name1 << " is older than " << name2 << endl;
}

if (age2 == age1)
{
cout << name2 << " is the same age as " << name1 << endl;
}

return 0;
}

Note: Strings can be read from the keyboard using the normal << operator, i.e.
cin << Name1;
However this does not work if the string contains spaces as it assumes that the string
ends at the first space. You couldn't read the name Joe Bloggs like this as only the
Joe would be read into Name1. A better method is to use the getline function, i.e.
cin.getline(Name1, 20);
This means "read characters from the keyboard into Name1, stopping when 19
characters have been read or when a new line character is encountered". Note that a
maximum of 19 and not 20 characters can be read, as space is left for the zero
character which terminates the string (section 3.7).

Exercise 8.2 Modify your program from exercise 3.2 to work with complex roots.
(answer on web site)
That is, if the value of ac b 4
2
is positive, display the results in the form:
Please enter the coefficients a, b and c: 1 1 -6

There are two real roots.
The roots are 2 and -3

Introduction to C++ Page 42
If the value of ac b 4
2
is negative, display the results as:
Please enter the coefficients a, b and c: 2 -4 10

There are two complex roots.
The roots are 1 +/- 2 j

where the real part is given by
a
b
2
, and the imaginary part by
2
2
4a
b
a
c
.
Hint: you will need to store the real part in one variable (e.g. Real) and the imaginary
part in another (e.g Imag). Output the results using a line such as
cout << "The roots are " << Real << " +/- " << Imag << " j" << endl;
Thirdly, if the value of ac b 4
2
is zero, display the results as:
Please enter the coefficients a, b and c: 1 8 16

There are two identical roots.
Both roots are -4.0.


,Z Nested bIocks
"if" blocks can be nested inside each other. For example
//Program 8.2. Nested if blocks
//(Complete program available on the WWW)

if (y >= 0)
{
if (x >= 0)
cout << "The point is in the North-East quadrant" << endl;
else
cout << "The point is in the North-West quadrant" << endl;
}
else
{
if (x >= 0)
cout << "The point is in the South-East quadrant" << endl;
else
cout << "The point is in the South-West quadrant" << endl;
}

It can be confusing as to which if statement each else statement is paired with.
Although the braces {} can be omitted from the above program, they make the logical
structure more explicit and are strongly recommended. Note also how the blocks are
indented.
,3 Common errors
8.3.1 Equality is checked using two equals signs. Be very careful of the following:
Introduction to C++ Page 43
if (x = y) // should be if (x == y)
cout << "x is equal to y" << endl;

This does not compare x to y. One equals sign alone does not compare the two values,
but assigns the right hand value to the left hand variable, and returns that value. This
condition will therefore be true if y is not equal to zero, which is almost certainly not
what was intended!

8.3.2 Do not finish an if statement with a semicolon.
if (x == y);
cout << "x is equal to y" << endl;

Here the second line is not part of the if condition, which finishes at the first semi-
colon and does nothing useful. In this case the second line will always be executed
regardless of the result of the if condition.

8.3.3 It is common to want to specify ranges of variables such as -1 < x < 1.
However care has to be taken in programming this. It should take the form in C++:
if (-1 < x && x < 1)
or, using brackets to make the order of evaluation explicit:
if ((-1 < x) && (x < 1))
The statement
if (-1 < x < 1)
is valid C++, but does something totally different which is almost certainly not what
the programmer intended.
Aside: This is like saying
if ((-1 < x) < 1)
(-1 < x) is either true (1) if x > -1 or false (0) if x -1.
The outer bracket is then evaluated, i.e. ((1 or 0) < 1).
This is true if the inner bracket is 0.
So the overall expression is true only if x -1!

8.3.4 If more than one statement is conditional, they must be in a block surrounded by
braces. What is wrong with the following?
int i, j, Bigger;

Introduction to C++ Page 44
cin >> i >> j;

if (i > j)
Bigger = i;
cout << "i has the larger value" << endl;

if (j > i)
{
Bigger = j;
cout << "j has the larger value" << endl;
}


8.3.5 It is best not to use the == operator with floating point numbers, as round-off error
may cause a slight difference in numbers that are supposed to be equal. For example,
the following may give a false result (try it!):
double x = 1.0 / 3.0;

if (1.0 / x == 3.0)
cout << "x is equal to 1/3" << endl;

A better solution is to check if the absolute value of the difference is less than a very
small amount (fabs is a function declared in math.h which returns the absolute value
of a double value).
const double TINY = 1.e-8;

double x = 1.0 / 3.0;

if (fabs(3.0 - 1.0 / x) < TINY)
cout << "x is equal to 1/3" << endl;

,4 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, sections 4.1-4.5
Introduction to C++ Page 45
9 Repeuted Ioops: the "whiIe" "do ,,, whiIe" und
"for" stutements
key points
Loops are used for executing a block of code several times.
In while loops the condition is tested at the start of the loop.
In do ... while and for loops the condition is tested at the end of the loop.
break can provide an alternative route for exiting the loop from anywhere within
it.
If you get stuck in an infinite loop try closing the window, or Ctrl-C. If these dont
work try Ctrl-Alt-Del.

It is often necessary to repeat blocks of code either a preset number of times or until an
event occurs or a condition is satisfied. There are three different commands for doing
this in C++; while, do ... while and for.
9,1 whiIe
The form of the while statement is:
while (condition)
statement or block of statements

This is similar to the if statement described previously; the statement or block of
statements is executed only if the condition is true. However the difference is that the
statement or block of statements is repeated while the condition remains true, stopping
only when the condition becomes false.
Introduction to C++ Page 46
For example, a program to calculate the square of a number, repeating until the
number is zero, could be:
#include <iostream>
using namespace std;

// Program 9.1. To calculate the square of numbers entered at the
// keyboard, stopping when the number is zero

int main(void)
{

// we need to initialise Number to a non-zero value, otherwise the
// while loop will never be executed.
int Number = -1;

while (Number != 0)
{
cout << "Enter a number (0 to stop the program): ";
cin >> Number;

cout << "The square of " << Number << " is " <<
Number * Number << endl;
}
return 0;
}

Exercise 9.1 Modify the above program to stop when the number is negative.
9,Z do ,,, whiIe
In the while statement, the condition is checked before the statement or block of
statements is executed. In the do ... while statement however, the condition is
checked afterwards. This means that the statement or block of statements is executed
at least once.
The form of the do ... while statement is:
do
statement or block of statements
while (condition);


Introduction to C++ Page 47
Program 9.2 below is similar to program 9.1, but a do ... while loop is used.
#include <iostream>
using namespace std;

// Program 9.2. To calculate the square of numbers entered at the
// keyboard, stopping when the number is zero

int main(void)
{
// No need to initialise Number in this case, as the condition is
// checked at the end.
int Number;
do
{
cout << "Enter a number (0 to stop the program): ";
cin >> Number;

cout << "The square of " << Number << " is " <<
Number * Number << endl;
}
while (Number != 0);

return 0;
}

Exercise 9.2 Modify the above program to stop when the number is less than -100 or
greater than +100 (warning: see section 8.3.3!).
(Answer on website)
9,Z,1 EumpIe
Heres a program to count the number of passes and fails in a class of students.
#include <iostream>
using namespace std;

// Program 9.3. To count the number of passes and fails in a
// class of students.
// The user enters p for pass, f for fail,
// q to finish the list.

int main(void)
{
int Passes = 0, Fails = 0; //initialise counters to zero
char Result;

do
{
cout << "Enter result (p = pass, f = fail, q = quit): ";
cin >> Result;

if (Result == p)
Passes++; //add one to pass list
else if (Result == f)
Fails++; //add one to failure list

}
while (Result != q); //finish if q pressed

cout << "Passes: " << Passes << endl;
cout << "Fails: " << Fails << endl;

return 0;
Introduction to C++ Page 48
}

Exercise 9.3 Download the above program and modify it to accept upper case (P, F, Q)
as well as lower case inputs.
(Answer on website)
9,3 for
The for statement is very similar to the while statement. It takes the form
for (initialisation; condition; change)
statement or block of statements


This is equivalent to the while structure
initialisation
while (condition)
{
statement(s)
change
}

For example, the following program displays the squares of the numbers from 1 to 10:
#include <iostream>
using namespace std;

// Program 9.4. To calculate the square of numbers from 1 to 10
// using a for loop

int main(void)
{

int Number;

for (Number = 1; Number <= 10; Number++)
{
cout << "The square of " << Number << " is " <<
Number * Number << endl;
}

return 0;
}

Exercise 9.4 Modify program 9.4 to calculate the squares of numbers in reverse order
from 10 to 1.

Program 9.4 can also be implemented using a while loop as follows:
#include <iostream>
using namespace std;
Introduction to C++ Page 49

// Program 9.5. To calculate the square of numbers from 1 to 10
// using a while loop

int main(void)
{
int Number = 1;
while (Number <= 10)
{
cout << "The square of " << Number << " is " <<
Number * Number << endl;

Number++;
}
return 0;
}

Whether a while loop or a for loop is used is a matter of preference. It is often
convenient to use for loops when looping a pre-set number of times (programs 9.4,
9.5, 9.6).
9,4 Nested Ioops
In the same way as if blocks, loops can be nested inside each other. It is possible to
nest any combination of if, for, while and do ... while blocks inside each
other. The program is made clearer if each loop or block is indented. Here's an
example.

#include <iostream>
using namespace std;

// Program 9.6. To display the multiplication table for numbers
// from 1 to 12

int main(void)
{

int i, j;

//for each row (i):
for (i=1; i<=12; i++)
{
//and each column (j):
for (j=1; j<=12; j++)
{
// display the numbers padded with spaces to a width
// of 4 characters, to line up the columns
cout.width(4);

cout << i * j;
}

// go to a new line
cout << endl;
}

// and another new line at the end.
cout << endl;

Introduction to C++ Page 50
return 0;
}

The for (j=1... loop is entirely within the for (i=1... loop. Note also how
each block of statements is indented.
Exercise 9.5 Modify program 9.6 to use while loops.
9, breuk
It is often useful to provide the condition for exiting a loop not at the start (as in the
while or for loop) or at the end (as in the do ... while loop) but somewhere
in the middle. This can be done using the break statement, e,g,
#include <iostream>
using namespace std;

// Program 9.7. To calculate the square of numbers entered at the
// keyboard, stopping when the number is zero

int main(void)
{
int Number;

while (1) // an infinite loop, as 1 means true
{
cout << "Enter a number (0 to stop the program): ";
cin >> Number;

// if Number is zero, exit the loop
if (Number == 0)
break;

cout << "The square of " << Number << " is " <<
Number * Number << endl;
}
return 0;
}

Exercise 9.6 Modify program 9.7 to stop when the number is less than -100 or greater
than +100.
break can be used to provide more than one exit routes from a loop.
Note that, when there are nested loops, break only exits from the innermost loop,
and the outer loops will continue.
9,,1 EumpIe: EponentiuI function
An example of a function for calculating e
x
is given below. The main program calls
this function, and also calls the exp function from the standard library for comparison
of results. The function makes use of the expansion
...
! 3 2
1 ) exp(
3 2
+ + + + =
x x
x x
Introduction to C++ Page 51
It calculates the terms until the magnitude of the term falls below the value of
ACCURACY. Note that the n
th
term in the series is given by the previous term
multiplied by x/(n-1). This is far more efficient than calculating each term from
scratch.

#include <iostream>
#include <math.h>
using namespace std;

//Program 9.8. To calculate exp(x) using a user-defined function,
//and to compare the result with the standard library function.

double Exponential (double x); //function prototype

int main(void)
{
double Value;
cout << "Enter a value: ";
cin >> Value;

// display the result of your Exponential function and the
// standard exp function
cout << Exponential (Value) << " " << exp(Value) << endl;

return 0;
}

double Exponential (double x)
{
const double ACCURACY = 1.e-10;
const int MAXTERM = 100;

// Term is the value of each term, starting at 1
double Term = 1;

// Result is the sum of the terms
double Result = Term;

// i is the number of terms
int i=1;

do
{

//increment counter
i++;

//calculate new term from previous term
Term *= x/(i-1);

//add to result
Result += Term;

//print out terms for debugging, if required
// cout << i << " " << Result << " " << Term << endl;

}
// stop when term becomes small enough or limit is reached
while (fabs(Term) > ACCURACY && i < MAXTERM);

return Result;
}

Introduction to C++ Page 52
Exercise 9.7 Modify the above program to calculate the sine of a value and compare with
the C++ library sin function, using the expansion
+ + =
! 7 ! 5 ! 3
) sin(
7 5 3
x x x
x x
Note that the n
th
term is -x
2
/[(2n-2)(2n-1)] times the previous term.
(Answer on website)
9, Infinite Ioops: uborting your progrum
You may sometimes find that your program gets 'stuck' and you cannot get out of it.
This may be due to an 'infinite loop' which the computer cycles around endlessly and
mindlessly. To get out of this, try and close the window. If this doesnt work press and
hold down the Ctrl, Alt and Delete keys together. This should abort the program
although the computer may hang up altogether. Save your program regularly!
9,7 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, sections 4.6-4.7
Introduction to C++ Page 53
10 Input/output
key points
cin >> is used for reading from the keyboard. It works with most variable types.
cout << is used for writing to the screen.
Files can be created for input using the ifstream class.
Files can be created for output using the ofstream class.
Once the files are opened, they can be read from or written to in the same way as
for the cin and cout streams.

All programs to be useful must be able to output data, and all but the most trivial need
to input data. The simplest method for input/output in C++ is to use stream classes.
We have already looked at reading variables from the keyboard using the cin stream,
and writing to the screen using the cout stream. cin is an instance of the
ifstream class, and cout an instance of the ostream class.
Most reading and writing operations are carried out using the >> and << operators, for
example:
cin >> nPoints; //puts the next number from the input stream
//into variable nPoints

cout << "The number is " << nPoints; //Sends the text "The number is "
//followed by the value of
//nPoints to the output stream.
The >> and << arrows imply the direction of data transfer, i.e. from the keyboard
(cin), to the screen (cout).
Some other useful functions in the cin and cout classes are:
cin.getline(char buffer[], int length, char delimiter='\n')
reads a whole line of text into buffer, until length-1 characters have been entered
or the delimiter character (the default is the enter key) is entered (see exercise 5.1).
cout.precision(int n);
sets the number of significant figures for all subsequent numbers.

cout.flags(ios::scientific);
selects scientific (exponential) notation for all subsequent numbers.

Introduction to C++ Page 54
Aside: This rather obscure notation is related to classes. ios is the base class from
which the ifstream and ofstream classes are derived. :: means member of the
class. scientific is a static constant defined in the ios class.

cout.flags(ios::fixed);
selects fixed point notation.
10,1 FiIe input/output
Data can be written to or read from a file in a similar way to the above. However,
rather than using cin and cout, which relate to the standard input/output devices, i.e.
the keyboard and screen, it is first necessary to open the file. This is done by declaring
an object of class ifstream (for reading from file) or ofstream (for writing to a
file). These classes are defined in the header file fstream.
This can be done in two ways:
#include <fstream> //at start of program
using namespace std;

ifstream InputFile("Filename.dat");

ofstream MyFile("Datalog.dat");
or
#include <fstream> //at start of program
using namespace std;

ifstream InputFile;
InputFile.open("Filename.dat");

ofstream OutputFile;
OutputFile.open("Datalog.dat");


It is usually worth checking that the file has been created correctly.
if (!InputFile)
{
cerr << "Failed to open Filename.dat" << endl;
//cerr is like cout but is used for error messages
}
Introduction to C++ Page 55
Data can be read from or written to the file in the same way as with cin and cout:
InputFile >> xData >> yData;

OutputFile << "Time = " << Time
<< " Acceleration = " << Acceleration << endl;

OutputFile << x << \t << y << \tendl; //numbers separated by tabs
The file is automatically closed when the ifstream or ofstream object is
destroyed. It can also be closed explicitly:
InputFile.close();

10,1,1 EumpIe: Writing to u fiIe
This program is similar to program 9.6 but writes the multiplication table to a file
instead of to the screen. In this case tab characters are used to separate the numbers.

#include <fstream>
#include <iostream>

using namespace std;

// Program 10.1. To write to a file the multiplication table
// for numbers from 1 to 12

int main(void)
{
const int MAXLENGTH = 80;
char FileName[MAXLENGTH];

//read file name
cout << "Enter file name: ";
cin.getline(FileName, MAXLENGTH);

//open file
ofstream OutputFile(FileName);

// check if file was opened successfully
if (!OutputFile)
{
cerr << "Failed to open " << FileName << endl;
return 1;
}

//for each row (i):
for (int i=1; i<=12; i++)
{
//and each column (j):
for (int j=1; j<=12; j++)
{
// display the numbers as a table, separated by tabs
OutputFile << i * j << \t;
}

// go to a new line
OutputFile << endl;
}

// and another new line at the end.
Introduction to C++ Page 56
OutputFile << endl;

//close file
OutputFile.close();

return 0;
}

Open the file created by this program and look at its contents.
10,Z Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, chapter 12
Introduction to C++ Page 57
11 Assignment Z - Drugster SimuIution
The task here is to write a program to simulate the motion of your model dragster.
You can investigate the effect of various physical parameters on the performance, and
predict effects such as wheelspin and wheelies. The intention is that this can be used
for optimising the design of your dragster.
11,1 First stuge
You need to calculate the speed and distance travelled by the dragster as time passes.
This is done using numerical integration. There are several techniques available for
numerical integration and the simplest is Euler's method which we shall be using here.
In this method, calculations are performed at equally spaced intervals in time. The new
velocity and distance travelled are calculated from the values of velocity, distance and
acceleration at the previous timestep, that is:


where the subscript i represents values at the i
th
timestep, and i+1 the values at the next
timestep. s represents distance, v velocity and a acceleration. t is the time step.
The first thing we need to do is to set the values for the physical constants such as
mass, inertia etc., and to set the starting values of velocity, distance and time to zero.
We also need to set a suitable value for the timestep. The smaller the timestep is the
more accurate the results will be, but the program will take longer to run. A value of
0.05 seconds is about right.
You next need a loop so that the calculations can be performed repeatedly until it has
travelled the required distance. A while, do ... while or for loop could be
used for this. We want to simulate the progress of the dragster over a distance of 10m
but its probably wise to finish the loop either when this distance has been reached or
when a time limit has been reached (without a time limit, you may be stuck in the loop
for ever).
In the loop, the acceleration needs to be calculated. Firstly you need to find the spring
extension x. The extension x can be calculated from the distance travelled s using the
equation
W
A
initial
R
R
s x x = .
The initial spring extension x
initial
is 100mm. R
A
is the axle radius around which the
thread is wound, and R
W
the driving wheel radius.
t a v v
t v s s
i i i
i i i
+ =
+ =
+
+
1
1
Introduction to C++ Page 58
You then need to find the spring tension T. At the initial spring extension the spring
tension T is 18.3N. The spring tension reduces linearly with extension to 3.3N at x = 0.
The spring tension T at an extension x can be found by linear interpolation between
these two values.
The tractive force F can then be found from the equations
if x>0,
W
A
R
R
T F =
if x 0, F = 0 (thread disengaged from axle).
The acceleration can then be calculated using the equation
2
W
R
J
M
drag F
a
+

= .
M is the total mass and J the moment of inertia of the driving wheels and axle.
The same drag function as in assignment 1, with appropriate values, can be used.
The time, distance and speed then need to be updated as follows:
Time = Time + TimeStep;
Distance = Distance + Speed * TimeStep;
Speed = Speed + Acceleration * TimeStep;
The order of this is important. The value of Speed must be calculated after the value of
Distance, as the old value of Speed is used in the calculation of Distance.
You need to save the results to a data file. The name of the file should be entered by
the user when the program is run. The program should check that the file has been
opened correctly (section 10.1). The values of time, acceleration, velocity and distance
should be saved to the file at each timestep, separated by tab characters with a new
line for each timestep. Results can be plotted using Microsoft Excel.
11,Z Finishing touches
Once the basic program works properly, you can add a few enhancements to it. Two
possible problems are wheelspin and wheelies. These can be predicted by calculating
the shift in load during acceleration. The normal reactions at the front and rear wheels
are (see your Solid Mechanics notes):
L
H
Ma
L
B
Mg N
F
=
L
H
Ma
L
B L
Mg N
R
+

=
where L is the wheelbase length, B is the horizontal distance of the centre of gravity in
front of the rear axle, and H the height of the centre of gravity from the ground.
Save these two reactions to the results file along with time, acceleration, velocity and
distance.
Introduction to C++ Page 59
Assuming rear wheel drive, the dragster will wheelie if the front reaction N
F
< 0.
Wheelspin will occur if the tractive force
R
N F > , where is the friction coefficient.
Your program should display a suitable warning on the screen if a wheelie or
wheelspin occurs. Note that, if wheelspin or a wheelie occurs, the calculated
acceleration, velocity and distance are invalid; the acceleration calculation assumes no
wheelspin or wheelieing.
11,3 Using your progrum
Use your program to predict the behaviour of your model dragster. Measure or
estimate the parameters as well as possible. You can estimate the wheel moment of
inertia by some rough calculations. You may be able to set up a simple experiment to
measure the friction coefficient .
Experiment with the parameters to see what effect each one has on the performance.
Try and optimise the dragster for best performance, within the constraints of your
dragster design. You will need to use sensible estimates for some parameters such as
rolling resistance and air resistance. Finally, compare your predicted time with your
actual result in the competition.
11,4 Submission
Use a spreadsheet program (such as Microsoft Excel) to plot a graph of velocity,
distance, acceleration, front reaction and rear reaction against time, for your optimised
dragster.
As before, ensure that your program is well structured and commented. Also ensure
that the graph is well presented. Attach the program file (named using your username
followed by 2, e.g. en1abc2.cpp) and the Excel file to an email and send to the
instructor.
Introduction to C++ Page 60
1Z Arruys
It is often necessary to work with several items of related data values. For example, in
the next stages of the car acceleration program you will be using five gear ratios and a
large number of engine torque values for different speeds and throttle settings.
Usually the best way to handle this sort of data is to use arrays. An array can contain a
pre-defined number of values of the same type.
1Z,1 One-dimensionuI Arruys
One-dimensional arrays are suitable for a sequential set of values, such as the gear
ratios in the car problem. They are defined as in the following examples.
double GearRatio[5]; //defines an array of type double with
//space for 5 values

const int NUMBER_OF_CLASSES = 10;
int ClassSize[NUMBER_OF_CLASSES]; //defines an array of type int with
//space for 10 values.

char Text[1000 * 3]; //defines an array of type char with
//space for 3000 characters
A pair of square brackets is used to indicate that an array is being defined. The size of
the array is indicated by the number in those brackets. When declaring an array this
number must be an integer constant.
Arrays can be initialised using curly brackets {}. Char arrays can also be initialised
using double quotes "" (section 3.7). For example
double GearRatio[5] = {1.2, 2.3, 3.4, 4.5, 5.6};

int ClassSize[] = {32, 25, 33}; //The size in brackets can be omitted
//if the array is initialised.

char Text[20] = "Enter text here"; //Here only the first 16 of the
//20 characters are initialised.


Array elements can be accessed (i.e. read or changed) by specifying an index or
subscript in square brackets. For example:
GearRatio[1] = 1.234;

int GearNumber = 3;
EngineSpeed = GearRatio[GearNumber] * RoadSpeed;

for (int i = 0; i< 5; i++)
cin >> GearRatio[i];

x[i+1] = x[i] + dx * timestep;

Introduction to C++ Page 61
The index must be an integer. Valid index values are from 0 to size of the
array minus 1. Take care that the index is within this range, as going outside of this
range will cause unpredictable problems which can be very difficult to track down.

Exercise 12.1 What is wrong with these statements?
(Answer at end of booklet)
double Temperature[];

int DataSet[32.5];

double X[10];
X[10] = 33.6;

int i = 3;
double y[i];

1Z,Z Pussing urruys to functions
Arrays can be arguments to functions. For example, take the following function
header:
double GetMean(int n, double Data[])
Note that the square brackets can be empty; there is no need to declare the size of the
array here as the amount of memory needed by the array is decided and allocated in
the program that calls this function.
1Z,Z,1 EumpIe
#include <iostream>
using namespace std;

//Program 12.1. To calculate the mean of a set of data.


double GetMean(int n, const double Data[])
{
double Sum = 0.0;
for (int i = 0; i < n; i++)
{
Sum += Data[i];
}
return (Sum / n);
}

int main()
{
const int MaxNumber = 20;
double Value[MaxNumber];

int Number;

cout << "Enter number of values: ";
cin >> Number;

for (int i = 0; i < Number; i++)
Introduction to C++ Page 62
{
cout << "Enter value number " << i + 1 << ": ";
cin >> Value[i];
}
cout << "The mean value is " << GetMean(Number, Value);
return 0;
}

Note that, when calling the function, the array name (Value) is used without square
brackets. The array name without brackets actually refers to the address in memory of
the first element of the array, i.e. the address of Value[0].

Exercise 12.2 This program will fail if the user attempts to enter more than 20 values.
Modify it so that the user is warned and corrective action taken if this
occurs.

There is a subtle difference between passing an array to a function and passing a
variable to a function. The whole array is not copied to the function (this would be
very inefficient); only the address of the start of the array is copied to the function.
This means that the array is passed by reference (section 5.2). The function can change
the values in the array and those changes will be carried back to the calling program.
To prevent it changing the values, the const keyword can be used as in program
12.1.

Aside: This is an example of the use of pointers. A pointer is basically a variable or
constant containing the memory address of some data. Pointers provide great
flexibility and are a key part of the C++ language. They can also cause very confusing
code and errors which can be extremely difficult to debug. They are only touched on
in this course.
1Z,3 MuIti-dimensionuI urruys
Two-dimensional arrays are often used for storing matrices, data maps or multiple data
sets. They are defined and referenced in C++ by using two sets of square brackets.
double xMatrix[3][4];
xMatrix[0][1] = 3.2;
The first index or subscript represents the number of rows, the second the number of
columns. Further pairs of brackets can be added to create more dimensions.
When a multi-dimensional array is passed to a function, the value of the first
dimension does not need to be specified in the function prototype and header, but the
others do. For example:
Introduction to C++ Page 63
int InvertMatrix(double X[][4]);
This is because the matrix is stored in memory one row at a time, i.e.
X[0][0] X[0][1] X[0][2] X[0][3] X[1][0] X[1][1] X[1][2] etc.

That is, element X[i][j] of the array is stored (i * 4 + j) values from the start of the
array. The compiler needs to know how many columns there are in order to determine
the correct address of each element.
1Z,3,1 EumpIe
#include <fstream>
#include <iostream>
#include <math.h>
using namespace std;

//Program 12.2. To call a function to invert a 2x2 matrix,
//and to calculate the product of two matrices.

int Invert2x2(const double A[][2], double B[][2])
{
const double TINY = 1.e-10;

//calculate determinant
double det = A[0][0]*A[1][1] - A[0][1]* A[1][0];

if (fabs(det) < TINY)
return 1; //error condition, avoiding divide by zero

//now invert matrix.
B[0][0] = A[1][1] / det;
B[0][1] = -A[0][1] / det;
B[1][0] = -A[1][0] / det;
B[1][1] = A[0][0] / det;

return 0; // successful return
}

int main()
{
//define a square matrix containing the values
// (1 2)
// (3 4)
double X[2][2] = {{1.0, 2.0},{3.0, 4.0}};
// The inner set of braces are optional. For example
// double X[2][2] = {1.0, 2.0, 3.0, 4.0};
// is valid.

double Y[2][2];

//call function to invert matrix. If it returns a non-zero value
//this indicates an error, in which case stop the program.
if (Invert2x2(X, Y) != 0)
return 1;

//display results
cout << "X = (" << X[0][0] << " " << X[0][1] << ")" << endl
<< " (" << X[1][0] << " " << X[1][1] << ")" << endl
<< endl;

cout << "Y = (" << Y[0][0] << " " << Y[0][1] << ")" << endl
<< " (" << Y[1][0] << " " << Y[1][1] << ")" << endl
Introduction to C++ Page 64
<< endl;

//now calculate X * Y as a check
double Z[2][2];
int i, j;

for (i=0; i<2; i++)
for (j=0; j<2; j++)
Z[i][j] = X[i][0] * Y[0][j] + X[i][1] * Y[1][j];

cout << "X * Y = (" << Z[0][0] << " " << Z[0][1] << ")" << endl
<< " (" << Z[1][0] << " " << Z[1][1] << ")" << endl
<< endl;

return 0;
}


Exercise 12.3 Download and run this program. Modify it to call the function again to
calculate the inverse of Y, and display the result on the screen (the result
should be equal to X).
(solution on website)

Introduction to C++ Page 65

1Z,3,Z EumpIe: reuding from u fiIe
#include <iostream>
#include <fstream>
using namespace std;

// Program 12.3. To read from a file into an array the multiplication
// table created in program 10.1 for numbers from 1 to 12, and use
// this as a look-up table to display the product of two numbers
// (ok, it would be far easier just to calculate the product,
// but it shows the principle, and a similar technique will be used
// in assignment 3).

int main(void)
{
const int MAXLENGTH = 80;
char FileName[MAXLENGTH];

//read file name
cout << "Enter file name: ";
cin.getline(FileName, MAXLENGTH);

//open file
ifstream InputFile(FileName, ios::in);

// check if file was opened successfully
if (!InputFile)
{
cerr << "Failed to open " << FileName << endl;
return 1;
}

int x[13][13]; // declare 2-dimensional array to store data.
// Note that zero indices are not used, hence
// dimension is 13, not 12

for (int i=1; i<=12; i++) // for each row (i):
for (int j=1; j<=12; j++) //and each column (j):
InputFile >> x[i][j];

//close file
InputFile.close();

int a, b;
cout << "Enter first and second numbers (integers from 1 to 12): ";
cin >> a >> b;

cout << "Product of " << a << " and " << b << " is "
<< x[a][b] << endl;

return 0;
}

Exercise 12.4 The task is to calculate the torque of an engine at a given speed and throttle
setting from measured data. This exercise is more involved than others. The
program produced will be used as part of assignment 3, so it should be your
own work.
Download the data file 'Torque.dat' from the web. This file contains engine torque
values for 15 different engine speeds and 10 different throttle settings. Write a
program to read the data from this file into a one-dimensional array for speed and a
Introduction to C++ Page 66
two-dimensional array for torque. The data values are stored in the file in the
following sequence:
s[0] t[0][0] t[0][1] t[0][2] t[0][9]
s[1] t[1][0] t[1][1] t[1][2] t[1][9]
. . .
. . .
. . .
s[14] t[14][0] t[14][1] t[14][2] t[14][9]
where s[i] is the i
th
value of speed, and t[i][j] is the torque at the i
th
value of speed and
the j
th
throttle setting.
Hint: you will need to use nested for loops, rather like in program 12.3. The outer
loop will repeat for each row. Within this loop, you will need to read the speed value,
then enter another loop to read each torque value in that row.
Now add some user input so that the user enters a required throttle setting Throttle
(an integer from 0 to 9) and engine speed EngineSpeed. The task then is to write a
function to calculate the torque at that speed and throttle setting. The speed that you
require is unlikely to correspond with the speeds for the torque map, so you will need
to use linear interpolation to estimate the torque from the nearest values in the speed
array. You need to do the following:
Create an EngineTorque function in which the Speed and Torque arrays s and
t and the required speed EngineSpeed are passed as arguments to the function.
Now scan through the speed array s to find the two values above and below the
required speed EngineSpeed. You want to find the lowest value of i where
s[i] is greater than EngineSpeed. This can be done using a while loop, do
while loop or for loop. The loop should start with i=1, and scan through the
speed array, finishing either when s[i] > EngineSpeed, or when you reach
the last value of the speed array. One way of doing this is as follows.
for (int i = 1; i < 14; i++) //loop through speed array
{
//Is speed array value s[i] greater than required speed?
if (s[i] > EngineSpeed)
{
//If yes, jump out of loop. Otherwise look at next speed in array.
break;
}
}
The torque values at the two adjacent speeds s[i-1] and s[i] and throttle
setting Throttle are t[i-1][Throttle] and t[i][Throttle]
respectively. Interpolate between these two values to find the torque at the required
speed. You can use the following formula for linear interpolation, where (x
A
, y
A
)
and (x
B
, y
B
) are two known points and we want to find y
R
at an x coordinate x
R
.
( )( )
y y
y y x x
x x
R A
B A R A
B A
= +


Return the calculated torque value from the function.
Introduction to C++ Page 67
Call the function from the main program and display the calculated torque on the
screen.
Ensure that your program works and calculates an appropriate value if the required
speed is outside the range of speeds in the array. It should extrapolate from the two
nearest values. You can actually use the same equation for extrapolation as you used
for interpolation, provided that the index i is set to the appropriate value.
Write a main function to test this function, in which the user is asked for an engine
speed and throttle setting. The main function should then call the function to calculate
torque, and display it on the screen. You can test it with the following values.
Throttle 3 6
EngineSpeed 500 rad/sec 700 rad/sec
Torque 27.07634 Nm 68.13225 Nm
1Z,4 Further reuding
Capper, D. M., Introducing C++ for Scientists, Engineers and Mathematicians,
Springer-Verlag, chapters 6 & 7
Introduction to C++ Page 68
13 Assignment 3
In assignment 1 you wrote a program to calculate the acceleration of a car at a given
speed. In assignment 2 you modelled the motion of a model dragster. The task now is
to combine these two in order to create a car simulation program including gear
changes and 3D graphics (the graphics routines have been pre-written and are easy to
link in).
13,1 NumericuI integrution
Its probably best to start with your program from assignment 1. You need to add in
the integration loop and equations, and file opening and writing, from assignment 2.
We want to simulate the progress of the car over a preset distance (say 1000m). For
now we will stay in 5th gear, but later we will be changing gear as well.
The values of time, acceleration, velocity and distance should be saved to the file at
each timestep, separated by tab characters with a new line for each timestep. Results
can be plotted using Microsoft Excel.
Make sure that the program works before going on to the next stage.
13,Z Seur chunges
You now need to modify your program so that it will start from a specified gear, to be
entered from the keyboard when the program is run.
This can be done by defining an array containing the gear ratios and an integer
containing the current gear number. For example:
const int MAX_GEAR = 5;

const double Ratio[MAX_GEAR] = {47.89, 29.94, 20.29, 14.41, 10.75};

int GearNumber = 1;
The gear number could be entered by the user when the program is run.
You now need to use a specific element of the array when performing your
calculations, i.e. Ratio[GearNumber - 1] and not just Ratio. Note that the
array subscripts go from 0 to MAX_GEAR - 1 and not from 1 to MAX_GEAR, so you
will need to subtract 1 from GearNumber to get the correct index.
You now need to change your program so that it changes gear automatically when the
engine speed reaches pre-determined values. It should change down a gear when the
engine speed falls below 1200 rev/min (126 rad/s) provided it is not already in first
gear. It should change up a gear when the engine speed rises above 6000 rev/min (628
rad/s) and it is not already in top gear. You can assume that the gear change takes
place instantaneously. This can be done either in the main program or in a new
function.
Introduction to C++ Page 69
You can simulate slipping the clutch at very low speed by setting a minimum engine
speed of 1000 rev/min (105 rad/s). In the torque calculation function, check if the
engine speed falls below this value and, if it does, just set it to this value.
13,3 CuIcuIution of torque
Note: you may omit this section if you dont have enough time and go straight to
section 13.4. Your program will then be marked out of 70% rather than 100%.
The next stage of assignment 3 is to calculate the torque from an engine performance
map, rather than from the simple quadratic approximations that you have been using.
The Torque.dat file (on the web) contains torque data for a range of speeds and
throttle settings. You need to write a function to read this file and calculate the torque
for a particular engine speed and throttle setting.
The best way to tackle this is to start off with your solution to exercise 12.4. Paste the
important bits into your main program. You need the bit to read the data from the file
into two arrays, which goes into your main function before the main loop. You also
need the torque calculation function, which replaces the previous torque function.
13,4 Adding Sruphics
Once your program is working (with or without section 13.3) you can link it up with
some pre-written graphics functions to produce a simple animation. Ok, its not up to
PlayStation 2 standard, but its a start!
See the instructions on the web page (in the Source Code for Selected Examples
section). Make sure that your program works properly before you do this, as it will be
more difficult to debug once the graphics are incorporated.
You can drive the car from the keyboard using the number keys 0-9 to set the
throttle, the letter b to brake (press repeatedly to increase the braking), the arrow keys
to steer and q to stop.
There are bonus marks for any improvements to the graphics!
13, Setting it murked
When you have finished the above stages, run the program to produce a results file for
the following conditions:
Initial speed 0
Throttle 9
Initial gear 1
Total distance 1000m
Now use a spreadsheet program (such as Microsoft Excel) to plot a graph of velocity
and acceleration against time.
Introduction to C++ Page 70
As before, ensure that your program is well structured and commented. Also ensure
that the graph is well presented. Attach the program file (named using your username
followed by 3, e.g. en1abc3.cpp) and the Excel file to an email and send to the
instructor.
14 From here,,,
If you have succeeded in getting through the above exercises and assignments, you are
well on the way towards being a competent programmer. Obviously there is a lot to
remember, and real familiarity with the C++ language will only come with continued
practice. You will be using C++ in the second year for numerical analysis and real-
time system control, and possibly in your 3
rd
and 4
th
year projects.
You may well need to use C++ in your future job, or you may need to use another
language such as Fortran, Visual BASIC, Java, Pascal or MATLAB. Having learnt
one language it is relatively easy to learn another as the principles are usually very
similar.
Good luck!
Introduction to C++ Page 71
1 Answers to seIected eercises
Exercise 3.2
"hello"
'\'


Exercise 4.2
cout << 3.0 * 2.0 / 4.0 << endl;
This gives the correct answer of 1.5, because all the constants are
floating point.

cout << 3 * 2 / 4 << endl;
This gives an answer of 1, because it is an integer expression which is
rounded down.

cout << 3.0 * (2 / 4) << endl;
This gives an answer of zero, because the integer sub-expression 2 / 4 is
evaluated to 0. That zero is then converted to a floating point value (0.0)
to be multiplied by 3.0.

cout << 3 * (2.0 / 4) << endl;
This gives the correct answer of 1.5, because the sub-expression 2.0 / 4 is
of floating point type (the 3 and 4 are converted automatically to floating
point values).

cout << (3 * 2.0) / 4 << endl;
This gives the correct answer of 1.5, because the sub-expression 3 * 2.0 is
of floating point type (again the 3 and 4 are converted automatically to
floating point values).

Exercise 5.1
cout << Number << " to the power 8 is " <<
Square( Square( Square (Number) ) ) << endl;
This gives the wrong answer for numbers of 15 or greater. It happens when the result
goes outside the range of the int variable type (see section 3.1).

Exercise 5.4
{
x = y; //x takes the value of y.
//By doing this, the original value of x is lost.

y = x; //y takes the new value of x.
//The result is that both x and y become equal
//to the old value of y.
}
Introduction to C++ Page 72

Exercise 8.1
if (age2 > age1)
{
cout << name2 << " is older than " << name1 << endl;
}

else if (age2 == age1)
{
cout << name2 << " is the same age as " << name1 << endl;
}

else
{
cout << name1 << " is older than " << name2 << endl;
}



Exercise 12.1
double Temperature[];
Need to specify the size of the array in brackets so that the compiler
knows how much space to allocate.

int DataSet[32.5];
The size of the array must be a whole number.

double X[10];
X[10] = 33.6;
Valid array indices are from 0 to 9. This will compile and link and may
work but is likely to corrupt the memory and crash the program.

int i = 3;
double y[i];
The size of the array must be a constant expression. Ok if the first line
was
const int i=3;

Das könnte Ihnen auch gefallen