Introduction To C++ Programming
Introduction To C++ Programming
August 1997
Contents
1 The Computer 11
1.1 Central Processing Unit . . . . . . . . . . . . . . . . . . . . . 13
1.2 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.2.1 Main memory . . . . . . . . . . . . . . . . . . . . . . . 14
1.2.2 External Memory . . . . . . . . . . . . . . . . . . . . . 14
1.3 Input/Output Devices . . . . . . . . . . . . . . . . . . . . . . 15
1.4 The system bus . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5 More about memory and information representation . . . . . 16
1.5.1 Representation of information in external memory . . 17
1.6 The execution cycle . . . . . . . . . . . . . . . . . . . . . . . 17
1.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.8 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 19
1.9 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 19
2 Programming Languages 20
2.1 Assembly Language . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 High level Languages . . . . . . . . . . . . . . . . . . . . . . . 22
2.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 23
3 Operating Systems 25
3.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.2 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 27
5 Algorithms 32
5.1 Describing an Algorithm . . . . . . . . . . . . . . . . . . . . . 33
5.2 Statements required to describe algorithms . . . . . . . . . . 35
5.3 Verifying the correctness of the algorithm . . . . . . . . . . . 37
5.3.1 Desk-checking . . . . . . . . . . . . . . . . . . . . . . . 38
1
5.4 Series Minimum and Maximum Algorithm . . . . . . . . . . . 38
5.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.6 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 42
5.7 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2
10 Conditions 79
10.1 Relational Expressions . . . . . . . . . . . . . . . . . . . . . . 79
10.2 Examples using Relational Operators . . . . . . . . . . . . . . 79
10.3 Logical Expressions . . . . . . . . . . . . . . . . . . . . . . . . 80
10.4 Examples using logical operators . . . . . . . . . . . . . . . . 81
10.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.6 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 82
10.7 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 83
11 The if statement 85
11.1 Examples of if statements . . . . . . . . . . . . . . . . . . . 85
11.2 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
11.3 Multiple Choice Questions . . . . . . . . . . . . . . . . . . . . 87
11.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3
15.6 Review questions . . . . . . . . . . . . . . . . . . . . . . . . . 112
15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
4
20 Top-down design using Functions 150
20.1 The need for functions . . . . . . . . . . . . . . . . . . . . . . 151
20.2 The mathematical function library in C++ . . . . . . . . . . 152
20.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
20.4 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 154
20.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
23 Arrays 176
23.1 Arrays in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . 177
23.1.1 Declaration of Arrays . . . . . . . . . . . . . . . . . . 177
23.1.2 Accessing Array Elements . . . . . . . . . . . . . . . . 178
23.1.3 Initialisation of arrays . . . . . . . . . . . . . . . . . . 180
23.2 Example Program: Printing Outliers in Data . . . . . . . . . 180
23.3 Example Program: Test of Random Numbers . . . . . . . . . 182
23.4 Arrays as parameters of functions . . . . . . . . . . . . . . . . 184
23.5 Strings in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . 186
23.5.1 String Output . . . . . . . . . . . . . . . . . . . . . . 187
23.5.2 String Input . . . . . . . . . . . . . . . . . . . . . . . . 187
23.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
23.7 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 190
23.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
5
About the course
Course contents
This course is intended as a first introduction to programming computers
using the C++ programming language. It is not assumed that the student
has done any programming before hence this course is not comprehensive
and does not cover all of C++. In particular it does not cover any of the
object-oriented features of C++, these are introduced in the following course
(Introduction to Computing II). Because this is a first programming course
emphasis is placed on the design of programs in a language-independent
fashion. A brief introduction to computers is also given.
The lessons of the course may be split into groups as follows:
6
• Lesson 2 - Programming Languages. Covers the various levels of
Programming Languages.
• Lesson 3 - Operating Systems. Covers the purpose of Operating
systems and the major types.
• Lesson 4 - Preparing a Computer Program. Covers the steps that
are carried out in going from a problem specification to having a
well-tested and reliable program to solve the problem.
3. About C++
7
• Lesson 17 - The do-while statement. An alternative way to carry
out repetition.
• Lesson 18 - The for statement. Repetition a set number of times
or as a control loop variable takes a set of values.
• Lesson 19 - Streams and External Files. How to input and output
data from and to external files.
• Lesson 21 - An introduction to User-defined functions in C++.
How to design your own functions.
• Lesson 22 - Further User-defined functions. Returning informa-
tion by parameters.
• Lesson 23 - Arrays. How to work with large collections of indexed
data.
Note that there is also a document ‘The Computer Exercises’ which gives
some help in using Windows and the Borland C++ compilers.
8
Week 5 Study Lessons 11 and 12 on if and if-else statements and im-
plement the exercise on programs with simple selection.
Week 6 Continue the study of selection mechanisms with Lessons 13 and
14 on nested if and if-else statements and the switch statement.
The switch statement is not as fundamental as the others so spend
less time on it than the other selection mechanisms.
Week 7 Study Lesson 15 on repetition constructs and practice designing
algorithms using repetition. Commence Lesson 16 on the while state-
ment.
Week 8 Continue Lesson 16 on the while statement. Also cover Lesson 17
on the do-while statement this week. Do not spend so much time on
it as on the more fundamental while statement.
Week 9 Cover Lesson 18 on the for statement. This statement is used
frequently and so is an important statement. Have a look at Lesson
19 on Streams and Files so that you can use an External file in the
last assignment.
Week 10 Study Lesson 20 on structured design using functions. This is a
very important Lesson. If you have time start on Lesson 21 on how to
construct C++ functions.
Week 11 Carry on with Lesson 21 on user-defined functions. Continue on
to Lesson 22. In carrying out the exercises in these Lessons you will
also get further practice on using the conditional and repetition control
structures.
Week 12 Study Lesson 23 which introduces the concept of arrays. Again
this is an important concept in programming. The exercises for this
chapter will provide you with more practice in the use of control struc-
tures and functions.
Week 13 Finish off the course and start revision.
Assessment
There will be two class assignments to carry out. One will be given out which
requires that you know the material up to and including Lesson 12. The
other will require that you know the material up to and including Lesson 20
(19 is not needed for the assignment). The first assignment will be worth 10%
in the final assessment and the second assignment will be worth 15% in the
final assessment. The remaining 75% will come from the class examination.
Further information will be available on the World Wide Web version of
the course.
9
Accessing the course on the World Wide Web
The course, and its successor Introduction to Computing II, are available on
the World Wide Web (WWW). You are assumed to know how to connect
to WWW. The course has been developed using Netscape as the browser,
but it should be possible to access it equally well with Microsoft’s Internet
Navigator, or with Mosaic. To access the course, use your browser to open
the URL
http://www.cee.hw.ac.uk/
This will present you with a page about the Department of Computing and
Electrical Engineering at Heriot-Watt University. Follow the link labelled
The page loaded will give general information about the courses. There will
also be reminders about approaching deadlines for coursework, and notifi-
cation of any corrections to parts of the course. (Any corrections will have
been made in the WWW version of the course, but this will enable you to
annotate your printed version of the notes.) You are advised to always enter
the course in this fashion. Saving bookmarks with your browser may cause
problems if any corrections cause extra sections or questions to be added to
the course.
Coursework should be submitted using electronic mail. Send any files re-
quested to [email protected], with clear indications of which assignment
is being submitted within the file.
Getting Help
Although the notes are intended to be comprehensive, there will undoubtedly
be times when you need help. There are two mechanisms for this. An
electronic mailing list has been set up at Heriot-Watt University which copies
messages submitted to it to all members of the course. The course organisers
and teachers receive all messages sent to this list. All students should join
this mailing list, and use it to replace the discussion that would normally
take place in a classroom. In order to join the mailing list, send an electronic
mail message to [email protected] with the following contents:
subscribe pathways
Once you have joined the list, messages to the list are sent as ordinary
electronic mail addressed to [email protected]
If your problems are of a more individual nature, you may prefer to send
them to the course teacher only, in which case an email message should be
addressed to [email protected]
10
Lesson 1
The Computer
11
12
1.1 Central Processing Unit
The Central Processing Unit (CPU) performs the actual processing of data.
The data it processes is obtained, via the system bus, from the main mem-
ory. Results from the CPU are then sent back to main memory via the
system bus. In addition to computation the CPU controls and co-ordinates
the operation of the other major components. The CPU has two main com-
ponents, namely:
It is worth noting here that the only operations that the CPU can carry
out are simple arithmetic operations, comparisons between the result of a
calculation and other values, and the selection of the next instruction for
processing. All the rest of the apparently limitless things a computer can
do are built on this very primitive base by programming!
Modern CPUs are very fast. At the time of writing, the CPU of a typical
PC is capable of executing many tens of millions of instructions per second.
1.2 Memory
The memory of a computer can hold program instructions, data values, and
the intermediate results of calculations. All the information in memory is
encoded in fixed size cells called bytes. A byte can hold a small amount
of information, such as a single character or a numeric value between 0 and
255. The CPU will perform its operations on groups of one, two, four, or
eight bytes, depending on the interpretation being placed on the data, and
the operations required.
There are two main categories of memory, characterised by the time it
takes to access the information stored there, the number of bytes which are
accessed by a single operation, and the total number of bytes which can
be stored. Main Memory is the working memory of the CPU, with fast
access and limited numbers of bytes being transferred. External memory
13
is for the long term storage of information. Data from external memory
will be transferred to the main memory before the CPU can operate on it.
Access to the external memory is much slower, and usually involves groups
of several hundred bytes.
14
There is also a small delay waiting for the appropriate section of the track
to rotate under the head. This latency is much smaller than the seek time.
Once the correct section of the track is under the head, successive bytes
of information can be transferred to the main memory at rates of several
megabytes per second. This discrepancy between the speed of access to the
first byte required, and subsequent bytes on the same track means that it
is not economic to transfer small numbers of bytes. Transfers are usually of
blocks of several hundred bytes or even more. Notice that the access time
to data stored in secondary storage will depend on its location.
The hard disc will hold all the software that is required to run the
computer, from the operating system to packages like word-processing and
spreadsheet programs. All the user’s data and programs will also be stored
on the hard disc. In addition most computers have some form of removable
storage device which can be used to save copies of important files etc. The
most common device for this purpose is a floppy disc which has a very lim-
ited capacity. Various magnetic tape devices can be used for storing larger
quantities of data and more recently removable optical discs have been used.
It is important to note that the CPU can only directly access data that
is in main memory. To process data that resides in external memory the
CPU must first transfer it to main memory. Accessing external memory to
find the appropriate data is slow (milliseconds) in relation to CPU speeds
but the rate of transfer of data to main memory is reasonably fast once it
has been located.
15
1.4 The system bus
All communication between the individual major components is via the sys-
tem bus. The bus is merely a cable which is capable of carrying signals
representing data from one place to another. The bus within a particular
individual computer may be specific to that computer or may (increasingly)
be an industry-standard bus. If it is an industry standard bus then there
are advantages in that it may be easy to upgrade the computer by buying a
component from an independent manufacturer which can plug directly into
the system bus. For example most modern Personal Computers use the PCI
bus.
When data must be sent from memory to a printer then it will be sent
via the system bus. The control signals that are necessary to access memory
and to activate the printer are also sent by the CPU via the system bus.
that is, one hundred, plus two tens, plus three units. Similarly the binary
number system builds all numbers from the bits 0 and 1, and powers of 2.
101 in the binary number system represents the number with value
1 × 22 + 0 × 21 + 1 × 20
which is of course the decimal number 5. Using the binary system allows
all computation inside the computer to take place using cheap two-state
electronic devices.
Modern computers organise information into small units called bytes
which hold eight bits, each bit representing a 0 or a 1. Each byte may
hold a single character of text or a small integer. Larger numbers, computer
instructions and character strings occupy several bytes.
The main memory can be thought of as a series of bytes numbered from
0, 1, 2, 3, . . . upwards, each byte containing a pattern of eight bits which
can be accessed by the CPU when it supplies the number, or Address, of
16
the byte required. For example consider the section of memory illustrated
below:
Address Contents
3168 10110111
3167 01000111
3166 01010101
The byte with the address 3167 contains the binary pattern 01000111.
Depending on circumstances the CPU may interpret this as an instruction,
as a number (or part of a number) or as a character. This pattern can
represent the character G in the ASCII character code that is used almost
universally now or it could represent the decimal number 71.
It is important to keep a clear distinction in your mind of the difference
between the address of a memory location and the contents of that memory
location.
17
the first instruction
while program not finished
{
fetch instruction from current instruction address
update current instruction address
execute the fetched instruction
}
1.7 Summary
• A computer consists of a Central Processing Unit(CPU), memory and
various devices which can be categorised as Input/Output Devices.
Information is communicated between these separate units by the Sys-
tems Bus.
• The memory of the computer is split into main memory and external
memory.
• Main memory is fast and limited in capacity. The CPU can only
directly access information in main memory. Main memory cannot
retain information when the computer is switched of. Main memory
consists of a series of numbered locations called bytes, each byte being
eight bits. The number associated with a byte is the address of the
byte.
18
• Each type of CPU has its own machine language, the set of instructions
it can obey.
100 00010010
99 10100101
98 11011101
19
Lesson 2
Programming Languages
where c( ) means ‘the contents of’ and the accumulator is a special register
in the CPU. This sequence of code then adds the contents of location 130
to the contents of the accumulator, which has been previously loaded with
the contents of location 129, and then stores the result in location 131.
Most computers have no way of deciding whether a particular bit pattern is
supposed to represent data or an instruction.
Programmers using machine language have to keep careful track of which
locations they are using to store data, and which locations are to form the
executable program. Programming errors which lead to instructions being
overwritten with data, or erroneous programs which try to execute part of
their data are very difficult to correct. However the ability to interpret
the same bit pattern as both an instruction and as data is a very power-
ful feature; it allows programs to generate other programs and have them
executed.
20
2.1 Assembly Language
The bookkeeping involved in machine language programming is very tedious.
If a programmer is modifying a program and decides to insert an extra data
item, the addresses of other data items may be changed. The programmer
will have to carefully examine the whole program deciding which bit patterns
represent the addresses which have changed, and modify them.
Human beings are notoriously bad at simple repetitive tasks; computers
thrive on them. Assembly languages are a more human friendly form of
machine language. Machine language commands are replaced by mnemonic
commands on a one-to-one basis. The assembler program takes care of con-
verting from the mnemonic to the corresponding machine language code.
The programmer can also use symbolic addresses for data items. The as-
sembler will assign machine addresses and ensure that distinct data items
do not overlap in storage, a depressingly common occurrence in machine
language programs. For example the short section of program above might
be written in assembly language as:
operation
code address
LOAD A
ADD B
STORE C
Obviously this leaves less scope for error but since the computer does not
directly understand assembly language this has to be translated into ma-
chine language by a program called an assembler. The assembler replaces
the mnemonic operation codes such as ADD with the corresponding binary
codes and allocates memory addresses for all the symbolic variables the pro-
grammer uses. It is responsible for associating the symbol A, B, and C with
an addresses, and ensuring that they are all distinct. Thus by making the
process of programming easier for the human being another level of process-
ing for the computer has been introduced. Assembly languages are still used
in some time-critical programs since they give the programmer very precise
control of what exactly happens inside the computer. Assembly languages
still require that the programmer should have a good knowledge of the in-
ternal structure of the computer. For example, different ADD instructions
will be needed for different types of data item. Assembly languages are still
machine specific and hence the program will have to be re-written if it is to
be implemented on another type of computer.
21
2.2 High level Languages
Very early in the development of computers attempts were made to make
programming easier by reducing the amount of knowledge of the internal
workings of the computer that was needed to write programs. If programs
could be presented in a language that was more familiar to the person solv-
ing the problem, then fewer mistakes would be made. High-level program-
ming languages allow the specification of a problem solution in terms closer
to those used by human beings. These languages were designed to make pro-
gramming far easier, less error-prone and to remove the programmer from
having to know the details of the internal structure of a particular computer.
These high-level languages were much closer to human language. One of the
first of these languages was Fortran II which was introduced in about 1958.
In Fortran II our program above would be written as:
C = A + B
which is obviously much more readable, quicker to write and less error-prone.
As with assembly languages the computer does not understand these high-
level languages directly and hence they have to be processed by passing them
through a program called a compiler which translates them into internal
machine language before they can be executed.
Another advantage accrues from the use of high-level languages if the
languages are standardised by some international body. Then each manu-
facturer produces a compiler to compile programs that conform to the stan-
dard into their own internal machine language. Then it should be easy to
take a program which conforms to the standard and implement it on many
different computers merely by re-compiling it on the appropriate computer.
This great advantage of portability of programs has been achieved for several
high-level languages and it is now possible to move programs from one com-
puter to another without too much difficulty. Unfortunately many compiler
writers add new features of their own which means that if a programmer uses
these features then their program becomes non-portable. It is well worth
becoming familiar with the standard and writing programs which obey it,
so that your programs are more likely to be portable.
As with assembly language human time is saved at the expense of the
compilation time required to translate the program to internal machine lan-
guage. The compilation time used in the computer is trivial compared with
the human time saved, typically seconds as compared with weeks.
Many high level languages have appeared since Fortran II (and many
have also disappeared!), among the most widely used have been:
22
COBOL Business applications
FORTRAN Engineering & Scientific Applications
PASCAL General use and as a teaching tool
C & C++ General Purpose - currently most popular
PROLOG Artificial Intelligence
JAVA General Purpose, gaining popularity rapidly,
All these languages are available on a large variety of computers.
2.3 Summary
• Each CPU has its own internal machine language. Programming at
this internal machine level is usually carried out in Assembly language
which is machine specific and relates on an instruction to instruction
basis to the internal machine language.
3. From the point of view of the programmer what are the major advan-
tages of using a high-level language rather than internal machine code
or assembler language?
23
(a) Program portability
(b) Easy development
(c) Efficiency
24
Lesson 3
Operating Systems
25
and workstations linked together with perhaps several larger, more powerful
computers which provide a large amount of computer power and file storage
facilities to the network. This allows many people access to computing
facilities and access to common data-bases, electronic mail facilities etc.
Networks may be local to a building or a small area (Local Area Network
(LAN)) or connect individual networks across the country or world (Wide
Area Network (WAN)).
A particular form of network operating system is a Timesharing op-
erating system. Many large modern computers are set up to serve many
simultaneous users by means of a time-sharing system. Each user has a
direct connection to a powerful central computer, normally using a Visual
Display Unit (VDU) which has a keyboard (and often a mouse) for user
input and a screen for feedback from the computer to the user. There may
be several hundred simultaneous users of a large computing system. Com-
puting is Interactive in that the time from a user entering a command
until a response is obtained will typically be a few seconds or less. The
Operating System will cycle in turn through each connected terminal and if
the terminal is awaiting computation will give it a Time-slice of dedicated
CPU time. This process is continuous thus each program receives as many
time-slices as it requires until it terminates and is removed from the list of
programs awaiting completion.
In a system with multiple users the operating system must also carry
out other tasks such as:
26
The user can further split this space into various other directories. For
example a lecturer writing a course may well set up a directory to contain
all the files relevant to the course. Within this directory it is best to organise
the files into groups by setting up various sub-directories, a sub-directory
to hold course notes, another to hold tutorials, another to hold laboratory
sheets etc. Within one of these directories, say the tutorials directory, will
be held the relevant files — tutorial1, tutorial2 etc. This hierarchical file
storage structure is analogous to the storage of related files in a filing system.
A filing cabinet could hold everything relevant to the course, each drawer
could hold a different sub-division, such as notes, and each folder within the
drawer would be a particular lecture.
Space will also be allocated on the server for system files. These also
will be allocated to directories to facilitate access by the operating system.
3.1 Summary
• The operating system provides an interface between the user and the
computer and controls the internal operation of the computer and its
peripherals. It also manages the users’ files and system utilities such
as compilers, editors, application packages etc.
27
(a) Manages the user’s files.
(b) Provides the system facilities.
(c) Provides the interface to allow the user to communicate with the
computer.
(d) Controls the various peripherals
28
Lesson 4
Preparing a Computer
Program
2. Analyse the problem and decide how to solve it. At this stage one
has to decide on a method whereby the problem can be solved, such a
method of solution is often called an Algorithm.
29
piler may find Syntax errors in the program. A syntax error is a
mistake in the grammar of a language, for example C++ requires that
each statement should be terminated by a semi-colon. If you miss this
semi-colon out then the compiler will signal a syntax error. Before pro-
ceeding any syntax errors are corrected and compilation is repeated
until the compiler produces an executable program free from syntax
errors.
5. The object code produced by the compiler will then be linked with
various function libraries that are provided by the system. This takes
place in a program called a linker and the linked object code is then
loaded into memory by a program called a loader.
6. Run the compiled, linked and loaded program with test data. This
may show up the existence of Logical errors in the program. Logical
errors are errors that are caused by errors in the method of solution,
thus while the incorrect statement is syntactically correct it is asking
the computer to do something which is incorrect in the context of the
application. It may be something as simple as subtracting two numbers
instead of adding them. A particular form of logical error that may
occur is a run-time error. A run-time error will cause the program
to halt during execution because it cannot carry out an instruction.
Typical situations which lead to run-time errors are attempting to
divide by a quantity which has the value zero or attempting to access
data from a non-existent file.
The program must now be re-checked and when the error is found it is
corrected using the Editor as in (3) and steps (4) and (5) are repeated
until the results are satisfactory.
7. The program can now be put into general use - though unless the
testing was very comprehensive it is possible that at some future date
more logical errors may become apparent. It is at this stage that good
documentation produced while designing the program and writing
the program will be most valuable, especially if there has been a con-
siderable time lapse since the program was written.
4.1 Summary
• Before a computer program can be written the requirements of the
application must be investigated and defined comprehensively and un-
ambiguously . This leads to the production of the requirements spec-
ification.
30
The first step in writing a computer program is to produce an algo-
rithm.
• Once the program has been compiled, linked and loaded it can be
tested with realistic test data. Testing may show up the presence of
logical errors in the program. These may lead to the production of
wrong results or cause the program to halt on a run-time error.
2. What types of error can occur in computing and at what stages of the
processes of producing a program do they occur?
4. A program runs without any errors being reported but outputs results
that are wrong, what type of error is likely to have caused this?
31
Lesson 5
Algorithms
32
In sorting 10,000 numbers into ascending order a ‘good’ algorithm executing
on a PC took less than a second while a ‘poor’ algorithm took over 10
minutes.
33
1 carry out any initialisations required.
2 while not reached end of file do
3 {
4 read in next number.
5 add the number to the accumulated sum.
6 increment the count of numbers input.
7 }
8 evaluate the average.
Note that the line numbers are not required, they are merely for refer-
ence. It is commonplace in computer algorithms that certain initialisations
have to be carried out before processing begins. Hence as a reminder that
this might be necessary a phrase is inserted to indicate that initialisation
may be required at the beginning of every algorithm description as in line
1. Once the rest of the algorithm has been developed this initialisation step
can be expanded to carry out any initialisations that are necessary.
At line 2 a statement is used which describes a loop. This loop executes
the statements contained between the brackets in lines 3–7 continuously as
long as the condition ‘not reached end of file’ remains true. The brackets
are used to show that the statements in lines 4, 5 and 6 are associated to-
gether and are executed as if they were one statement. Without the brackets
only statement 4 would be executed each time round the loop. This is not
the only repetition statement that may be used, others are possible and
will be seen later. In the body of the loop, lines 4–6, each instruction is
a simple executable instruction. Once the end of the file is reached then
control transfers from the loop to the next instruction after the loop, eval-
uating the average at line 8. This requires more expansion, since, if there
are no numbers input then the average cannot be evaluated. Hence line 8 is
expanded to:
8a if no numbers input
8b then print message ‘no input’
8c otherwise {
8d set average equal to the accumulated sum
8e divided by the number of numbers.
8f print the average.
8g }
Here a conditional statement has been used with the condition ‘no
numbers input’, if this is true then the statement after the then is executed,
while if it is not true the statement after the otherwise is executed. This
process is often called a ‘Selection’ process.
On studying the above algorithm it is obvious that the process carried
out is what a human being might do if given a sheet of paper with many
numbers on it and asked to find the average. Thus a person might run their
34
finger down the numbers adding them as they go to an accumulated total
until there were no more and then counting the number of numbers and
dividing the total by this number to get the average. When this is done it
is implicit in their reasoning that the total and the count will both start
of at zero before starting to process the numbers. This is not obvious to
the computer at all, hence it must be remembered in describing computer
algorithms to initialise all sum accumulation variables and counters suitably
before commencing processing. Also it must be ensured that processing
starts at the beginning of the file. Hence the initialisation (line 1) can be
expanded as follows:
Note that if there were no data items in the file then the first element
in the file would be the end-of-file marker. Thus the ‘while-loop’ condition
would be false initially so the loop would not be executed and the number
of numbers would remain at zero. This would ensure that the condition at
line 8a was true hence the appropriate message would be output.
The whole algorithm is now:
35
all be implemented using the while loop used in the previous section. The
following basic concepts are required:
1. The idea that statements are executed in the order they are written.
Sequence.
36
ins.open(infile);
total = 0;
count = 0;
while (!ins.eof())
{
ins >> number;
total = total + number;
count = count + 1;
}
if (count == 0)
{
cout << "No input" << endl;
}
else
{
average = total/count;
cout << "Average is "
<< average
<< endl;
}
ins.close(infile);
37
being empty. In this case the count is initialised to zero, the body of the loop
is never executed hence the number count remains at zero. The condition
‘number count is zero’ in the conditional statement is then true and the
appropriate message is output.
This form of informal reasoning should be applied to check an algorithm
before implementing it as a program.
5.3.1 Desk-checking
Another way of testing the logic of programs is to carry out a desk-check,
that is execute the statements of the algorithm yourself on a sample data
set. This method of course is not foolproof, you would have to be sure that
you traversed all possible paths through your algorithm, this might require
you to use many data sets. It is useful to use a tabular layout for this. For
example say the initial data file was
2 6 eof
*
2 6 eof 0 0 after initialisation
*
2 6 eof 2 1 2 after first loop execution
*
2 6 eof 6 2 8 after second loop execution
*
2 6 eof 6 2 8 4 exit loop, evaluate average
The * indicates the file element which is available for reading on the next
input statement. Obviously this gives the correct result for this file. This
simple file is adequate to check the general case here because there are only
two paths through this algorithm. The other path is the case where the file
is empty. This could be checked in the same way.
38
A user has a list of numbers and wishes to find the minimum
value and the maximum value in the list. A program is required
which will allow the user to enter the numbers from the keyboard
and which will calculate the minimum and maximum values that
are input. The user is quite happy to enter a count of the num-
bers in the list before entering the numbers.
initialise.
get count of numbers.
enter numbers and find maximum and minimum.
output results.
The algorithm is now made completely general to allow for a list with
no numbers in it, this may seem a bit stupid but it is not uncommon when
writing a general-purpose function to allow for the possibility of null input.
A user might change their mind after calling the program for example and it
is sensible that the program should respond sensibly if the user enters zero
for the count. Incorporating this into the algorithm above gives the next
version:
initialise.
get count of numbers.
if count is zero
then exit
otherwise {
enter numbers and find maximum
and minimum.
output results.
}
Once the count of the numbers is known then a loop has to be executed
that number of times, each time reading in a number and somehow using
that number in finding the maximum and minimum of the numbers. In this
loop the number of times the loop is executed is known, i.e. equal to the
count of numbers. Thus another type of repetition command is introduced:
loop n times
{
body of loop.
}
39
statement. Each time the loop is executed it is the instructions between
the braces that are executed.
Hence the following version of the algorithm:
initialise.
get count of numbers.
if count is zero
then exit
otherwise {
loop count times
{
enter a number.
process the number.
}
output results.
}
It has not yet been considered how to compute the maximum and min-
imum values so this has been indicated by using the phrase ‘process the
number’. Given a large list of numbers written down on a sheet of paper
how could the smallest number in the list be found in a methodical fashion?
One way would be to start at the beginning of the list and work through
the list systematically always remembering the smallest number seen so far,
whenever a number is found smaller than the memorised number the mem-
orised number is replaced by the smaller number. At the start of the list the
smallest number yet seen is of course the first number, and when the end of
the list is reached the memorised number is the smallest. Similarly for the
largest number. Hence the following expansion:
40
}
count = 5
numbers are 3 5 1 7 2
- - - - begin
5 - - - enter count
5 3 3 3 enter first number
5 5 5 3 first loop execution
5 1 5 1 second loop execution
5 7 7 1 third loop execution
5 2 7 1 final loop execution
The symbol ‘-’ has been used to indicate an unknown value. At the end
of execution of the algorithm large and small do hold the correct maximum
and minimum values
5.5 Summary
• An algorithm is a sequence of steps which will produce a solution to a
problem.
41
• An algorithm must be finite, non-ambiguous and effective.
(a) sequence
(b) selection
(c) repetition
2. What is a condition?
2. What is a condition?
4. How would you endeavour to show that an algorithm you have pro-
duced is correct?
42
5.8 Exercises
1. A program is required which will read in the breadth and height of a
rectangle and which will output the area and the length of the perime-
ter of the rectangle. Write an algorithm for this problem.
repeat
statement 1.
.
statement n.
until condition
repeat
enter and process data.
ask if user wishes to process more data.
read reply.
until reply is no
43
Now extend your algorithm for question 2 so that it repeats entering
the dimensions of rectangles and calculating the results. After each
calculation the user should be asked if they wish to continue.
44
Lesson 6
Before looking at how to write C++ programs consider the following simple
example program.
// Sample program
// IEA September 1995
// Reads values for the length and width of a rectangle
// and returns the perimeter and area of the rectangle.
#include <iostream.h>
void main()
{
int length, width;
int perimeter, area; // declarations
cout << "Length = "; // prompt user
cin >> length; // enter length
cout << "Width = "; // prompt user
cin >> width; // input width
perimeter = 2*(length+width); // compute perimeter
area = length*width; // compute area
cout << endl
<< "Perimeter is " << perimeter;
cout << endl
<< "Area is " << area
<< endl; // output results
} // end of main program
rect 1.cpp
45
1. Any text from the symbols // until the end of the line is ignored by the
compiler. This facility allows the programmer to insert Comments
in the program. Every program should at least have a comment in-
dicating the programmer’s name, when it was written and what the
program actually does. Any program that is not very simple should
also have further comments indicating the major steps carried out and
explaining any particularly complex piece of programming. This is
essential if the program has to be amended or corrected at a later
date.
2. The line
#include <iostream.h>
must start in column one. It causes the compiler to include the text of
the named file (in this case iostream.h) in the program at this point.
The file iostream.h is a system supplied file which has definitions in
it which are required if the program is going to use stream input or
output. All your programs will include this file. This statement is a
compiler directive — that is it gives information to the compiler
but does not cause any executable code to be produced.
void main()
All programs must have a function main. Note that the opening brace
({) marks the beginning of the body of the function, while the closing
brace (}) indicates the end of the body of the function. The word void
indicates that main does not return a value. Running the program
consists of obeying the statements in the body of the function main.
4. The body of the function main contains the actual code which is ex-
ecuted by the computer and is enclosed, as noted above, in braces
{}.
46
send the quoted characters to the output stream cout. The special
identifier endl when sent to an output stream will cause a newline to
be taken on output.
7. All variables that are used in a program must be declared and given a
type. In this case all the variables are of type int, i.e. whole numbers.
Thus the statement
declares to the compiler that integer variables length and width are
going to be used by the program. The compiler reserves space in
memory for these variables.
area = length*width;
evaluates the expression on the right-hand side of the equals sign using
the current values of length and width and assigns the resulting value
to the variable area.
9. Layout of the program is quite arbitrary, i.e. new lines, spaces etc. can
be inserted wherever desired and will be ignored by the compiler. The
prime aim of additional spaces, new lines, etc. is to make the program
more readable. However superfluous spaces or new lines must not
be inserted in words like main, cout, in variable names or in strings
(unless you actually want them printed).
6.1 Variables
A variable is the name used for the quantities which are manipulated by a
computer program. For example a program that reads a series of numbers
and sums them will have to have a variable to represent each number as it
is entered and a variable to represent the sum of the numbers.
In order to distinguish between different variables, they must be given
identifiers, names which distinguish them from all other variables. This is
similar to elementary algebra, when one is taught to write “Let a stand for
the acceleration of the body . . . ”. Here a is an identifier for the value of the
acceleration. The rules of C++ for valid identifiers state that:
An identifier must:
47
• not be a reserved word
Reserved words are otherwise valid identifiers that have special significance
to C++. A full list is given below in section 6.1.1. For the purposes of C++
identifiers, the underscore symbol, _, is considered to be a letter. Its use
as the first character in an identifier is not recommended though, because
many library functions in C++ use such identifiers. Similarly, the use of
two consecutive underscore symbols, __, is forbidden.
The following are valid identifiers
48
C++ Reserved Words
and and_eq asm auto bitand
bitor bool break case catch
char class const const_cast continue
default delete do double dynamic_cast
else enum explicit export extern
false float for friend goto
if inline int long mutable
namespace new not not_eq operator
or or_eq private protected public
register reinterpret_cast return short signed
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
Some of these reserved words may not be treated as reserved by older
compilers. However you would do well to avoid their use. Other compilers
may add their own reserved words. Typical are those used by Borland
compilers for the PC, which add near, far, huge, cdecl, and pascal.
Notice that main is not a reserved word. However, this is a fairly tech-
nical distinction, and for practical purposes you are advised to treat main,
cin, and cout as if they were reserved as well.
• It associates a type and an identifier (or name) with the variable. The
type allows the compiler to interpret statements correctly. For exam-
ple in the CPU the instruction to add two integer values together
is different from the instruction to add two floating-point values to-
gether. Hence the compiler must know the type of the variables so it
can generate the correct add instruction.
For the moment only four variable types are considered, namely, int,
float, bool and char. These types hold values as follows:
49
int variables can represent negative and positive integer values (whole num-
bers). There is a limit on the size of value that can be represented,
which depends on the number of bytes of storage allocated to an int
variable by the computer system and compiler being used. On a PC
most compilers allocate two bytes for each int which gives a range of
-32768 to +32767. On workstations, four bytes are usually allocated,
giving a range of -2147483648 to 2147483647. It is important to note
that integers are represented exactly in computer memory.
float variables can represent any real numeric value, that is both whole
numbers and numbers that require digits after the decimal point. The
accuracy and the range of numbers represented is dependent on the
computer system. Usually four bytes are allocated for float variables,
this gives an accuracy of about six significant figures and a range of
about −1038 to +1038 . It is important to note that float values are
only represented approximately.
bool variables can only hold the values true or false. These variables
are known as boolean variables in honour of George Boole, an Irish
mathematician who invented boolean algebra.
int i, j, count;
float sum, product;
char ch;
bool passed_exam;
which declares integer variables i, j and count, real variables sum and
product, a character variable ch, and a boolean variable pass_exam.
A variable declaration has the form:
type identifier-list;
50
type specifies the type of the variables being declared. The identifier-list is
a list of the identifiers of the variables being declared, separated by commas.
Variables may be initialised at the time of declaration by assigning a
value to them as in the following example:
int i, j, count = 0;
float sum = 0.0, product;
char ch = ’7’;
bool passed_exam = false;
which assigns the value 0 to the integer variable count and the value 0.0
to the real variable sum. The character variable ch is initialised with the
character 7. i, j, and product have no initial value specified, so the program
should make no assumption about their contents.
defines an integer constant days_in_year which has the value 365. Later in
the program the identifier days_in_year can be used instead of the integer
365, making the program far more readable.
The general form of a constant declaration is:
This defines a constant VatRate to have the value 17.5, however if the Gov-
ernment later changes this rate then instead of having to search through the
program for every occurrence of the VAT rate all that needs to be done is
51
to change the value of the constant identifier VatRate at the one place in
the program. This of course only works if the constant identifier VatRate
has been used throughout the program and its numeric equivalent has never
been used.
Constant definitions are, by convention, usually placed before variable
declarations. There is no limit on how many constant declarations can be
used in a program. Several constant identifiers of the same type can be
declared in the same constant declaration by separating each declaration by
a comma. Thus
const int days_in_year = 365,
days_in_leap_year = 366;
Note that it is illegal in C++ to attempt to change the value of a constant.
#include <iostream.h>
void main()
{
constant declarations
variable declarations
executable statements
}
Note that it makes complex programs much easier to interpret if, as
above, closing braces } are aligned with the corresponding opening brace {.
However other conventions are used for the layout of braces in textbooks
and other C++ programmers’ programs. Also additional spaces, new lines
etc. can also be used to make programs more readable. The important thing
is to adopt one of the standard conventions and stick to it consistently.
52
The following statement waits for a number to be entered from the key-
board and assigns it to the variable number:
cin >> number;
The general form of a statement to perform input using the input stream
cin is:
cin input-list;
where input-list is a list of identifiers, each identifier preceded by the input
operator >>. Thus
cin >> n1 >> n2;
would take the next two values entered by the user and assign the value of
the first one to the variable n1 and the second to the variable n2.
The program must read a value for each variable in the input-list before
it executes any more statements. The order in which the values are entered
must correspond to the order of the variables in the input-list and they
must be of the same type as the corresponding variable. They should be
separated by spaces. Normally, the C++ system will not pass any values to
the variables in the input-list until a complete line of input has been read,
i.e. until the return or enter key has been pressed. If more values are
supplied than are required to give each variable in the input-list a value, the
unused values will be used for any subsequent input statements using cin.
For example given the following declarations and input statement:
int count, n;
float value;
cin >> count >> value >> n;
the user could enter
23 -65.1 3
to assign 23 to count, -65.1 to value and 3 to n. There is no indication in
the data of which value is to be associated with which variable; the order
of the data items must correspond to the order of the variables in the input
list. The data items on input should be separated by spaces or new lines.
Any number of these will be skipped over before or between data items.
Thus the input above could equally well have been entered as:
23
-65.1 3
The following statement outputs the current value of the variable count
to the output stream cout, which is usually associated with the monitor.
The value will be printed on the current line of output starting immediately
after any previous output.
53
cout << count;
The general form of a statement to perform output using the output stream
cout is:
cout output-list;
will print Hello there on the current output line and then take a new line
for the next output. The statements:
will display, if the user enters 6.51 and 3.24 at the prompt, the following
output:
Note that a value written to cout will be printed immediately after any
previous value with no space between. In the above program the character
strings written to cout each end with a space character. The statement
6.513.24
54
6.6 Programming Style
As was remarked in note 6.4 above, any number of spaces and or new lines
can be used to separate the different symbols in a C++ program. The
identifiers chosen for variables mean nothing to the compiler either, but
using identifiers which have some significance to the programmer is good
practice. The program below is identical to the original example in this
Lesson, except for its layout and the identifiers chosen. Which program
would you rather be given to modify?
#include <iostream.h>
void main(
) { int a,b,
c,d; cout << "Length = "; cin >> a; cout<<"Width = "
;cin >> b; c = 2*(a+
b); d = a*b; cout
<< endl << "Perimeter is " <<
c << endl << "Area is " << d
<< endl;}
6.7 Summary
• An international standard for the C++ language is soon to be pro-
duced. This will make programs written in standard obeying C++
capable of being transported from one computer to another.
• Comments are ignored by the compiler but are there for the informa-
tion of someone reading the program. All characters between // and
the end of the line are ignored by the compiler.
• All variables and constants that are used in a C++ program must be
declared before use. Declaration associates a type and an identifier
with a variable.
• The type int is used for whole numbers which are represented exactly
within the computer.
• The type float is used for real (decimal) numbers. They are held to
a limited accuracy within the computer.
55
• Literal strings can be used in output statements and are represented
by enclosing the characters of the string in double quotation marks ".
(a) const
(b) y=z
(c) xyz123
(d) Bill
(e) ThisIsALongOne
(f) Sue’s
(g) two-way
(h) int
(i) so is this one
(j) amount
(k) 2ndclass
(a) cin
(b) cout
(a) //
(b) {
(c) ;
56
6.9 Review questions
1. Write a constant declaration that declares constants to hold the num-
ber of days in a week and the number of weeks in a year. In a separate
constant statement declare a constant pi as 3.1415927.
where the values of the radius, the area and the circumference are held
in variables rad, area, and circum.
include iostream.h
Main();
{
Float x,y,z;
cout < "Enter two numbers ";
cin >> a >> b
cout << ’The numbers in reverse order are’
<< b,a;
}
syntax.cpp
8. What data types would you use to represent the following items?
57
(a) the number of students in a class
(b) the grade (a letter) attained by a student in the class
(c) the average mark in a class
(d) the distance between two points
(e) the population of a city
(f) the weight of a postage stamp
(g) the registration letter of a car
6.10 Exercises
1. Using literal character strings and cout print out a large letter E as
below:
XXXXX
X
X
XXX
X
X
XXXXX
2. Write a program to read in four characters and to print them out, each
one on a separate line, enclosed in single quotation marks.
3. Write a program which prompts the user to enter two integer values
and a float value and then prints out the three numbers that are en-
tered with a suitable message.
58
Lesson 7
The main statement in C++ for carrying out computation and assigning val-
ues to variables is the assignment statement. For example the following
assignment statement:
average = (a + b)/2;
assigns half the sum of a and b to the variable average. The general form
of an assignment statement is:
result = expression ;
The expression is evaluated and then the value is assigned to the variable
result. It is important to note that the value assigned to result must be of
the same type as result.
The expression can be a single variable, a single constant or involve
variables and constants combined by the arithmetic operators listed below.
Rounded brackets () may also be used in matched pairs in expressions to
indicate the order of evaluation.
+ addition
- subtraction
* multiplication
/ division
% remainder after division (modulus)
For example
i = 3;
sum = 0.0;
perimeter = 2.0 * (length + breadth);
ratio = (a + b)/(c + d);
The type of the operands of an arithmetic operator is important. The
following rules apply:
59
• if both operands are of type int then the result is of type int.
• if either operand, or both, are of type float then the result is of type
float.
• if the expression evaluates to type int and the result variable is of type
float then the int will be converted to an equivalent float before
assignment to the result variable.
The last rule means that it is quite easy to lose accuracy in an assignment
statement. As already noted the type of the value assigned must be the same
type as the variable to which it is assigned. Hence in the following example
in which i is a variable of type int
i = 3.5;
the compiler will insert code to convert the value 3.5 to an integer before
carrying out the assignment. Hence the value 3 will be assigned to the
variable i. The compiler will normally truncate float values to the integer
value which is nearer to zero. Rounding to the nearest integer is not carried
out.
A similar problem arises with the division operator. Consider the fol-
lowing rule:
i = 1/7;
will assign the value zero to the integer variable i. Note that if the quotient
of two integers is assigned to a float then the same loss of accuracy still
occurs. Even if i in the above assignment was a variable of type float
1/7 would still be evaluated as an integer divided by an integer giving zero,
which would then be converted to the equivalent float value, i.e. 0.0, before
being assigned to the float variable i.
The modulus operator % between two positive integer variables gives the
remainder when the first is divided by the second. Thus 34 % 10 gives 4 as
60
the result. However if either operand is negative then there are ambiguities
since it is not well-defined in C++ what should happen in this case. For
example 10 % -7 could be interpreted as 3 or -4. Hence it is best to avoid
this situation. All that C++ guarantees is that
i % j = i - (i / j) * j
a + b * c
(a + b) * c or as a + (b * c) ?
( )
* / %
+ -
=
Thus
a + b * c
a + (b * c)
because the * has a higher priority than the +. If the + was to be evaluated
first then brackets would need to be used as follows:
(a + b) * c
If in any doubt use extra brackets to ensure the correct order of evalua-
tion.
It is also important to note that two arithmetic operators cannot be
written in succession, use brackets to avoid this happening.
61
7.2 Examples of Arithmetic Expressions
The following examples illustrate how some more complex mathematical
expressions can be written in C++.
f = float(i)/float(n);
62
or the names of constants already defined. Also note that the constant has
been given the value 5.0/9.0, if it had been defined by 5/9 then this would
have evaluated to zero (an integer divided by an integer) which is not the
intention.
#include <iostream.h>
void main()
{
const float mult = 5.0/9.0; // 5/9 returns zero
// integer division
const int sub = 32;
float fahr, cent;
cout << "Enter Fahrenheit temperature: ";
cin >> fahr;
cent = (fahr - sub) * mult;
cout << "Centigrade equivalent of " << fahr
<< " is " << cent << endl;
}
ftoc.cpp
#include <iostream.h>
void main()
{
int pence, pounds;
cout << "Enter the amount in pence: ";
63
cin >> pence;
cout << pence << " pence is ";
pounds = pence / 100; // note use of integer division
pence = pence % 100; // modulus operator -> remainder
cout << pounds << " pounds and "
<< pence << " pence" << endl;
}
ptolp.cpp
7.6 Summary
• Expressions are combinations of operands and operators.
(a) 19
(b) 27
2. Evaluate 7*3+2
(a) 23
(b) 35
3. Evaluate (4+2)*3
(a) 18
(b) 10
4. Evaluate 17/3
(a) 5
64
(b) 6
5. Evaluate 17%3
(a) 0
(b) 1
(c) 2
(d) 3
6. Evaluate 1/2
(a) 0
(b) 1
7. Evaluate 2*8/2*4
(a) 32
(b) 2
65
7.9 Exercises
1. Write a C++ program which reads values for two floats and outputs
their sum, product and quotient. Include a sensible input prompt and
informative output.
3. In many countries using the metric system, car fuel consumptions are
measured in litres of fuel required to travel 100 kilometres. Modify
your solution to question 2 so that the output now specifies the dis-
tance travelled in kilometres as well as in miles, and the fuel consumed
in litres as well as in gallons, and the consumption in litres per 100
kilometres as well as in miles per gallon. Use const for the conversion
factors between miles and kilometres, and gallons and litres.
66
Lesson 8
Further Assignment
Statements & Control of
Output
n = n + 1;
n = n - 1;
The ++ and -- operators here have been written after the variable they
apply to, in which case they are called the postincrement and postdecre-
ment operators. There are also identical preincrement and predecre-
ment operators which are written before the variable to which they apply.
Thus
Both the pre- and post- versions of these operators appear to be the
same from the above, and in fact it does not matter whether n++ or ++n
is used if all that is required is to increment the variable n. However both
67
versions of the increment and decrement operators have a side effect which
means that they are not equivalent in all cases. These operators as well as
incrementing or decrementing the variable also return a value. Thus it is
possible to write
i = n++;
What value does i take? Should it take the old value of n before it is
incremented or the new value after it is incremented? The rule is that a
postincrement or postdecrement operator delivers the old value of the vari-
able before incrementing or decrementing the variable. A preincrement or
predecrement operator carries out the incrementation first and then delivers
the new value. For example if n has the value 5 then
i = n++;
would set i to the original value of n i.e. 5 and would then increment n to 6.
Whereas
i = ++n;
sum = sum + x;
sum += x;
68
total += value; or total = total + value;
prod *= 10; or prod = prod * 10;
x /= y + 1; or x = x/(y + 1);
n %= 2; or n = n % 2;
Except for the case of the compound modulus operator %= the two
operands may be any arithmetic type. The compound modulus operator
requires that both operands are integer types.
69
Before looking at manipulators scientific notation for the display of
floating point numbers is considered. Scientific notation allows very large
or very small numbers to be written in a more convenient form. Thus a
number like 67453000000000000 is better written as 6.7453 × 1016 and a
number like 0.0000000000001245 is better written as 1.245 × 10−13 . C++
allows this type of notation by replacing the ‘ten to the power of’ by e or E.
Thus the above numbers could be written in C++ as 6.7453e16 and 1.245e-
13. These forms can be used in writing constants in C++ and in input and
output. On output, if a number is too large to display in six digits then
scientific notation will be used by default. For example 12345678.34 might
be output as 1.23457e+07.
The first manipulator considered is setiosflags, this allows the output
of floating point numbers to be
setiosflags(ios::flagname)
If more than one flag is to be set then another ios::flagname can be in-
cluded, separated by a | from the other setting in the above call. Thus the
following output statement would set fixed format with the decimal point
displayed:
This would ensure that a number like 1.0 would be displayed as 1.0 rather
than as 1. These flags remain in effect until explicitly changed.
Another useful manipulator is the setprecision manipulator, this takes
one parameter which indicates the number of decimal places of accuracy
to be printed. This accuracy remains in effect until it is reset. The
setprecision manipulator may be used when none of the iosflags have
been set. However there is some confusion over what constitutes precision,
some compilers will produce n digits in total and others n digits after the
point when setprecision(n) is used on its own. However if it is used after
the flags fixed or scientific have been set it will produce n digits after
the decimal point.
For the moment the most suitable setting of the iosflags for output are
fixed and showpoint.
The following portion of C++
70
float x, y;
x = 12.2345,
y = 1.0;
cout << setiosflags(ios::fixed | ios::showpoint)
<< setprecision(2);
cout << x << endl
<< y << endl;
would output
12.23
1.00
that is, in fixed format with two places after the point and the point dis-
played. Without the ios flag set to showpoint y would have been printed
as 1. If the decimal points have to be aligned then the field width has to be
set. This is done using the setw manipulator which takes a single parameter
which indicates the width of field in which the output value is to be placed.
The value is placed right-justified in the field. The field width remains in
effect only for the next data item displayed. Thus if the lines:
were added to the above portion of code the output would be:
12.23
1.00
12.23
1.00
Note 1: The file iomanip.h must be included if the above manipulators are
to be used. There are many more facilities available by using input/output
manipulators but the above is enough to allow the writing of programs that
produce sensible formatting of output in most cases.
Note 2: The output width is reset to the default after every variable
is output, so that it was necessary to use setw(7) twice, once before each
variable that was output.
71
// IEA Oct 1995
// Outputs a table of x and sin(x)
// Uses manipulators for output
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
void main()
{
float x;
int i;
cout << setiosflags(ios::fixed | ios::showpoint);
for (i = 0; i <= 16; i++ )
{
x = 0.1 * i;
cout << setprecision(1) << setw(4) << x;
cout << setprecision(6) << setw(10) << sin(x) << endl;
}
}
sin 1.cpp
8.5 Summary
• The unary increment and decrement operators are applied to integer
variables to increase or decrease the value by 1.
• If the increment (or decrement) operator is placed after the variable,
the operation takes place after the value has been returned.
72
• If the increment (or decrement) operator is placed before the variable,
the operation takes place before the value is returned.
variable op = expression
n = 7;
i = 4;
i = n++;
n = 5;
i = 9;
i = --n;
73
8.7 Exercises
1. Alter the program you wrote for exercise 2 in Lesson 7 so that the
printed values for mileage and tank contents have two digits printed
after the decimal point and the consumption in miles per gallon is
printed with one digit after the decimal point.
VAT at 8% 2.31
Total 31.20
Note that allowance has been made for future increases in the standing
charge to more than 10 pence per day, and for the number of days to
be anything up to 999. You may wish to consider suitable limits on the
amount of gas consumed, in order that the format of you final output
is not disrupted.
74
Lesson 9
Introduction to structured
design
75
1.4 Enter width
2. Calculate
2.1 Calculate perimeter as twice sum
of length and width
2.2 Calculate area as product of length and width
3. Output
3.1 Output perimeter
3.2 Output area
At this stage the problem has now been completely solved independent
of the language the program is to be written in. It is now simple to write
the program in any suitable programming language. In fact in Lesson 6 this
program was given as an example and Lesson 7 covered enough C++ to
allow this program to be written in C++.
Unfortunately not all problems are so simple to solve. Frequently the
simple idea of sequence used above is insufficient to describe the solution of
many problems.
Consider the following problem:
Write a program which enters the number of hours worked in a
week and an hourly rate of pay of an employee. The program
should output the wage of the employee. The employee is paid at
the normal hourly rate for the first forty hours and subsequently
at one and a half times the hourly rate.
The problem solution now appears fairly straightforward and modelling
it on the previous case an algorithm is written as follows:
1. Enter the hours worked and the hourly rate.
76
Thus using a conditional statement the algorithmic solution above could be
expanded as follows:
1. Enter
1.1 Prompt user for hours worked.
1.2 Enter hours worked.
1.3 Prompt user for hourly rate.
1.4 Enter hourly rate.
2. Calculate wage
2.1 If hours worked is less than or equal to forty
then
2.1.1 calculate normal wage.
otherwise
2.1.2 calculate over hours wage.
3. Output the wage
The details of working out the wage are not important here, what is
important is that in describing the solution a conditional statement was
used. Conditional statements are often characterised by the words
which carries out the process A if the condition evaluates to true and other-
wise carries out the process B. All programming languages have some form
of conditional statement. The conditional statements available in C++ are
considered in the following few lessons.
9.2 Summary
• The solution of a problem is usually best approached in a top-down
manner. Sub problems are identified and solutions are developed in
turn for each sub problem.
9.4 Exercises
1. In question 6 of Lesson 7 you wrote a program to process a gas bill. If
you haven’t already done so write down an algorithm for this program.
77
Now extend the algorithm so that the option of paying the bill by
installments is given. Thus as well as entering the numeric data the
user answers a question as to whether they wish to pay the bill in
full or by installments. If paid in installments then a five percent
interest charge is added to the total bill before VAT is charged. An
initial twenty percent must be paid initially and the remainder is paid
in three equal monthly installments. The output should indicate the
initial payment and monthly installment.
78
Lesson 10
Conditions
79
count != n
discriminant < 0.0
x * x + y * y < r*r
80
If i has the value 15, and j has the value 10, then the expression
(i > 10) && (j > 0) is evaluated by evaluating the relation i > 10 (which
is true), then evaluating the relation j > 0 (which is also true), to give
true. If j has the value −1 then the second relation would be false, so the
overall expression would be false. If i has the value 5, then the first relation
would be false and the expression will be false irrespective of the value of
the second relation. C++ does not even evaluate the second relation in this
situation. Similarly, if the first relation is true in an or (||) expression then
the second relation will not be evaluated. This short-circuit evaluation
enables many logical expressions to be efficiently evaluated.
Note that in the last example an actual truth value ( 0 - false) was
used as one of the operands of &&, this means that whatever the value of i
this logical expression evaluates to false (Why?). In these examples brackets
have been used to make the order of application of operators clear. However,
in the main, they are not strictly necessary if the precedence rules already
considered for arithmetic operators are extended to include relational and
logical operators. The consequent extended Operator Precedence Table
for C++ is:
highest - evaluate first
() brackets
! + - logical not, unary plus, unary minus
* / % multiply, divide, modulus
+ - add, subtract
< <= > >= less than, less than or equal,
greater than, greater than or equal
== != equal, not equal
&& logical and
|| logical or
= assignment
81
x + y < 10 && x/y == 3 || z != 10
shows that the operators are evaluated in the order /, +, <, ==, !=, && and
||. This is equivalent to bracketting the expression as follows:
Now that logical expressions (or conditions) in C++ have been covered
it is possible to move on and look at the conditional control structures in
C++.
10.5 Summary
• A condition or logical expression is an expression that can only take
the values false or true.
(a) 1 and 0
(b) Any numerical value
82
3. If a is 5, b is 10, c is 15 and d is 0 what are the truth values of the
following expressions?
(a) c == a+b
(b) a != 7
(c) b <=a
(d) a > 5
(e) a+d >= c-b
(f) d/a < c*b
(a) c == a+b || c == d
(b) a != 7 && c >= 6 || a+c <= 20
(c) !(b <= 12) && a % 2 == 0
(d) !(a >5) || c < a+b
c == a+b
a != 7
b <= a
a > 5
a+d >= c-b
d/a < c*b
c == a+b || c == d
a != 7 && c >= 6 || a+c <= 20
!(b <= 12) && a % 2 == 0
!(a >5) || c < a+b
83
5. Write a logical expression which returns true if a float variable x lies
between -10.0 and 10.0.
84
Lesson 11
The if statement
if (x > 0.0)
cout << "The value of x is positive";
if (condition)
statement
if (x > 0.0)
sum += x;
85
if (x >= 0.0)
{
sum += x;
poscount++;
}
if (x >= 0.0)
sum += x;
poscount++;
then if x was greater than zero the next statement would be executed, that
is x would be added to sum. However the statement incrementing poscount
would then be treated as the next statement in the program, and not as
part of the if statement. The effect of this would be that poscount would
be incremented every time, whether x was positive or negative.
The statements within a compound statement can be any C++ state-
ments. In particular, another if statement could be included. For example,
to print a message if a quantity is negative, and a further message if no
overdraft has been arranged:
if ( account_balance < 0 )
{
cout << "Your account is overdrawn. Balance "
<< account_balance << endl;
if ( overdraft_limit == 0 )
cout << "You have exceeded your limit. << endl;
}
In this case, the same effect could have been achieved using two if
statements, and a more complex set of conditions:
if ( account_balance < 0 )
cout << "Your account is overdrawn. Balance "
<< account_balance << endl;
if ( account_balance < 0 && overdraft_limit == 0 )
cout << "You have exceeded your limit. << endl;
11.2 Summary
• An if statement is used to execute a statement only if a condition is
true.
86
• Compound statements executed because an if condition is true can
contain any other C++ statement, including other if statements.
if (y > 0)
y += 2;
(a) 5
(b) 7
(c) 2
2. If p has the value 3 and max has the value 5, what will be the value of
the variable max after the following piece of C++ is executed?
if (p > max)
max = p;
(a) 5
(b) 3
3. If x has the value 5.0 what will be the value of the variable countneg
after the following piece of C++ is executed?
countneg = 0;
if (x < 0.0)
negsum = negsum + x;
countneg = countneg + 1;
(a) 0
(b) 1
(c) 5
countneg = 0;
if (x < 0.0)
{
negsum = negsum + x;
countneg = countneg + 1;
}
87
(a) 0
(b) 1
(c) 5
11.4 Exercises
In each of these exercises produce an algorithmic description before proceed-
ing to write the program.
2. Write a C++ program which when two integers x and y are input will
output the absolute difference of the two integers. That is whichever
one of (x-y) or (y-x) is positive. Think of all the cases that can arise
and consequently plan a set of test data to confirm the correctness of
your program.
88
Lesson 12
89
12.1 Examples of if-else statements
The following if-else statement adds x to a sum of positive numbers and
increments a count of positive numbers if it is positive. Similarly if x is
negative it is added to a sum of negative numbers and a count of negative
numbers is incremented.
if (x >= 0.0)
{
sumpos += x;
poscount++;
}
else
{
sumneg += x;
negcount++;
}
// IEA 1996
// Program to evaluate a wage
#include <iostream.h>
void main()
{
const float limit = 40.0,
overtime_factor = 1.5;
float hourly_rate, // hourly rate of pay
hours_worked, // hours worked
wage; // final wage
// Enter hours worked and hourly rate
cout << "Enter hours worked: ";
cin >> hours_worked;
cout << "Enter hourly_rate: ";
cin >> hourly_rate;
// calculate wage
if (hours_worked <= limit)
wage = hours_worked * hourly_rate;
90
else
wage = (limit + (hours_worked - limit) * overtime_factor)
* hourly_rate;
// Output wage
cout << "Wage for " << hours_worked
<< " hours at " << hourly_rate
<< " is " << wage
<< endl;
}
wages.cpp
Note that this program contains the minimal amount of comment that a
program should contain. Comments have been used to:
• indicate who wrote the program, when it was written and what it does.
91
// IEA 1996
// Program to produce pythagorean triples
// with input validation.
#include <iostream.h>
void main()
{
int m, n; // entered by user to generate triple
int t1, t2, t3; // The values of the triple
// input from user
cout << "Input values for m and n, m > n : ";
cin >> m >> n;
// now validate m and n
if (m > n)
{
t1 = m*m-n*n;
t2 = 2*m*n;
t3 = m*m+n*n;
cout << "The triple corresponding to "
<< m << " and " << n << " is "
<< t1 << " " << t2 << " " << t3
<< endl;
}
else
cout << "m must be greater than n!"
<< endl
<< "you entered m as " << m
<< " and n as " << n
<< endl;
}
pyth 1.cpp
Note that the values of m and n entered by the user are printed as part of
the output. This is good practice. Programs should not only display results
but should give some indication of the data that produced the results. In
this case the input data set was produced in full since it was small. In
situations where the input data set was large it might not be realistic to
reproduce it all but an indication such as
Results produced from Data Set No 23
might be output. This is vital if a listing of results is to mean anything at
a future date.
92
12.4 Example Program: Area and Perimeter of
Rectangle
Exercise 2 of Lesson 5 required an algorithm which given two values for the
breadth and height of a rectangle would output the area and perimeter of
the rectangle. However depending on whether the breadth and height were
equal or not different messages would be output indicating whether it was
a rectangle or a square. A suitable algorithm for this would be
// IEA 1996
// Calculates area and perimeter of a rectangle
// after input of breadth and height. Distinguishes
// a square from a rectangle.
#include <iostream.h>
void main()
{
int breadth, height; // of rectangle
int perimeter, area; // of rectangle
// input breadth and height
cout << "Enter breadth and height: ";
cin >> breadth >> height;
// calculate perimeter and area
perimeter = 2*(breadth+height);
area = breadth*height;
if (breadth == height)
cout << "Area and perimeter of square are ";
else
cout << "Area and perimeter of rectangle are ";
// output area and perimeter
cout << area << " " << perimeter
<< endl;
93
}
rect 2.cpp
Note how portions of the algorithmic description have been used as com-
ments within the program. Remember that successive values sent to the
output stream cout will each be printed immediately after the previous
output value. Hence in the program above the printing of the actual val-
ues for the area and perimeter will be printed directly after the information
string on the same line. If a new line is required then send the end of line
marker endl to cout.
12.5 Summary
• An if-else statement is used to choose which of two alternative state-
ments to execute depending on the truth value of a condition.
(a) 5
(b) 7
(c) 3
(d) 2
94
12.7 Review Questions
1. If x has the value 3.5 when the following statement is executed what
value would be assigned to y?
if (x + 1 <= 3.6)
y = 1.0;
else
y = 2.0;
if (x >= y)
sum += x;
cout << "x is bigger" << endl;
else
sum += y;
cout << "y is bigger" << endl;
12.8 Exercises
In each of these exercises produce an algorithmic description before proceed-
ing to write the program.
1. Write a C++ program which when two integers x and y are input will
output the absolute difference of the two integers. That is whichever
one of (x-y) or (y-x) is positive. Think of all the cases that can arise
and consequently plan a set of test data to confirm the correctness of
your program.
2. Write a C++ program which will compute the area of a square (area = side2 )
base ∗ height
or a triangle (area = ) after prompting the user to type
2
the first character of the figure name (t or s).
95
3. Percentage marks attained by a student in three exams are to be en-
tered to a computer. An indication of Pass or Fail is given out after
the three marks are entered. The criteria for passing are as follows:
A student passes if all three examinations are passed. Additionally a
student may pass if only one subject is failed and the overall average
is greater than or equal to 50. The pass mark for an individual subject
is 40.
Write a C++ program to implement this task.
96
Lesson 13
97
This version is not recommended since it does not make it clear that
only one of the assignment statements will be executed for a given value of
x. Also it is inefficient since all three conditions are always tested.
If nesting is carried out to too deep a level and indenting is not consistent
then deeply nested if or if-else statements can be confusing to read and
interpret. It is important to note that an else always belongs to the closest
if without an else.
When writing nested if-else statements to choose between several al-
ternatives use some consistent layout such as the following:
if ( condition1 )
statement1 ;
else if ( condition2 )
statement2 ;
. . .
else if ( condition-n )
statement-n ;
else
statement-e ;
Assume that a real variable x is known to be greater than or equal to
zero and less than one. The following multiple choice decision increments
count1 if 0 ≤ x < 0.25, increments count2 if 0.25 ≤ x < 0.5, increments
count3 if 0.5 ≤ x < 0.75 and increments count4 if 0.75 ≤ x < 1.
if (x < 0.25)
count1++;
else if (x < 0.5)
count2++;
else if (x < 0.75)
count3++;
else
count4++;
Note how the ordering of the tests here has allowed the simplification
of the conditions. For example when checking that x lies between 0.25 and
0.50 the test x < 0.50 is only carried out if the test x < 0.25 has already
failed hence x is greater than 0.25. This shows that if x is less than 0.50
then x must be between 0.25 and 0.5.
Compare the above with the following clumsy version using more com-
plex conditions:
if (x < 0.25)
count1++;
else if (x >= 0.25 && x < 0.5)
count2++;
98
else if (x >= 0.5 && x < 0.75)
count3++;
else
count4++;
13.1 Summary
• Nested if and if-else statements can be used to implement decisions
which have more than two outcomes.
• In nested if-else statements each else is associated with the nearest
preceding if which has no else already associated with it.
(a) 8
(b) 6
(c) 1
(a) 7
(b) 5
(c) 0
99
if (speed > 30)
fine = 50;
else if (speed > 40)
fine = 75;
else if (speed > 50)
fine = 100;
13.4 Exercises
1. Extend the mark-processing exercise 3 in Lesson 12 as follows. Print
out the student’s average mark (to the nearest integer) and also in-
clude a grade A to F alongside the average mark as defined in review
question 2 above.
100
Lesson 14
In the last Lesson it was shown how a choice could be made from more
than two possibilities by using nested if-else statements. However a less
unwieldy method in some cases is to use a switch statement. For example
the following switch statement will set the variable grade to the character
A, B or C depending on whether the variable i has the value 1, 2, or 3. If
i has none of the values 1, 2, or 3 then a warning message is output.
switch (i)
{
case 1 : grade = ’A’;
break;
case 2 : grade = ’B’;
break;
case 3 : grade = ’c’;
break;
default : cout << i
<< " not in range";
break;
}
switch ( selector )
{
case label1 : statement1 ;
break;
case label2 : statement2 ;
break;
. . .
case labeln : statementn ;
break;
default : statementd ; // optional
101
break;
}
The selector may be an integer or character variable or an expression that
evaluates to an integer or a character. The selector is evaluated and the
value compared with each of the case labels. The case labels must have
the same type as the selector and they must all be different. If a match is
found between the selector and one of the case labels, say labeli , then the
statements from the statement statementi until the next break statement
will be executed. If the value of the selector cannot be matched with any
of the case labels then the statement associated with default is executed.
The default is optional but it should only be left out if it is certain that
the selector will always take the value of one of the case labels. Note that
the statement associated with a case label can be a single statement or a
sequence of statements (without being enclosed in curly brackets).
102
switch (day)
{
case 1 :
case 7 : cout << "This is a weekend day";
break;
case 2 :
case 3 :
case 4 :
case 5 :
case 6 : cout << "This is a weekday";
break;
default : cout << "Not a legal day";
break;
}
Remember that missing out a break statement causes control to fall
through to the next case label — this is why for each of the days 2–6 ‘This is a
weekday’ will be output. Switches can always be replaced by nested if-else
statements, but in some cases this may be more clumsy. For example the
weekday/weekend example above could be written:
if (1 <= day && day <= 7)
{
if (day == 1 || day == 7)
cout << "This is a weekend day";
else
cout << "This is a weekday";
}
else
cout << "Not a legal day";
However the first example becomes very tedious—there are eight alterna-
tives! Consider the following:
if (day == 1)
cout << "Sunday";
else if (day == 2)
cout << "Monday";
else if (day == 3)
cout << "Tuesday";
.
.
else if (day == 7)
cout << "Saturday";
else
cout << "Not a legal day";
103
14.2 Summary
• A switch statement selects the next statement to be executed from
many possible statements. The selection is made depending on the
value of a selector variable which can only be an integer or a character.
• If the selector variable does not match any of the case labels then the
statements associated with the default label will be executed.
x = 3;
switch ( x ) {
case 1: c = ’A’; break;
case 2: c = ’B’; break;
case 3: c = ’C’; break;
default: c = ’F’; break;
}
(a) A
(b) B
(c) C
(d) F
>=70 ‘A’
60-69 ‘B’
104
50-59 ‘C’
40-49 ‘D’
30-39 ‘E’
<30 ‘F’
14.5 Exercises
1. Amend the program you wrote for Exercise 1 in Lesson 13 so that it
uses a switch statement to assign the grade. Use the idea suggested in
Review question 3 above.
105
Lesson 15
106
A user is to enter positive real values from the keyboard when
prompted by the program. To signal end of input the user en-
ters a negative number. When data entry has terminated the
program should output the minimum positive value entered, the
maximum positive value entered and the average of the positive
values entered. If there is no data entry (the user enters a nega-
tive number initially) then the program should output a message
indicating that no data has been entered.
initialise.
enter first value.
while (value is positive)
{
process value.
enter a value.
}
if no data entry
then output ‘no data entry’
otherwise
{
evaluate average.
output results.
}
process value:
add value to accumulated sum.
add one to count of number of values.
if value is bigger than saved maximum then
107
put value in saved maximum.
if value is less than saved minimum then
put value in saved minimum.
3. variables for the saved maximum and minimum — at the first execu-
tion of process value the only previous value is the first value, hence
the initialisation is to set the saved maximum and the saved minimum
to this value.
If no data is entered then this can be recognised by the fact that count
will be zero after execution of the while statement. Finding the average
merely requires dividing the sum by the count of values and output is fairly
obvious. Thus the final version is:
108
output count, average, maximum and minimum.
}
Note that if no data is entered then the terminating negative value will
be assigned to minimum and maximum. This does not matter because in
this case no use is made of these variables.
A program is required which will read in the marks as above for each
student and will output for each student, in one line, the above information
together with a final mark for each subject. The final mark in each subject
is 70% of the examination mark plus 30% of the coursework mark. The
average final mark for each subject should also be output. End of input is
to be signalled by input of a negative candidate number. A first algorithmic
description of the required program is:
initialise.
enter candidate number.
while candidate number is positive
{
enter marks for candidate.
process marks.
output results for candidate.
enter candidate number.
}
calculate subject averages.
output subject averages.
109
set sum1 and sum2 to zero.
set count to zero.
enter candidate number.
while candidate number is positive
{
enter s1, cw1, s2, cw2. // the four candidate marks
increment count.
set final1 to 0.7*s1+0.3*cw1.
set final2 to 0.7*s2+0.3*cw2.
add final1 to sum1.
add final2 to sum2.
output candidate number, s1, cw1, s2, cw2, final1, final2.
enter candidate number.
}
set subject1 average to sum1/count.
set subject2 average to sum2/count.
output subject1 average.
output subject2 average.
Note that this algorithm would fail if the first candidate number entered
was negative. The statement loop in the while statement would not be exe-
cuted and hence count would retain its initial value of zero. This would lead
to a division by zero when an attempt was made to calculate the averages.
It is often difficult to decide whether a program should cope gracefully with
non-existent data, after all why would a user use the program if they had no
data to enter? However a typing error may lead to the entry of unsuitable
data and it is preferable that the program should recover gracefully from
this situation rather than fail with an obscure run-time error later. This
algorithm could do this by either checking the sign of the first candidate
number entered and terminating with a suitable message if it is negative
or could recognise the situation by checking that count is non-zero before
proceeding to calculate the average.
This algorithm could be extended by adding various facilities to it, for
example indicating for each student whether they have passed judged by
some criteria. See the exercises for possible extensions for you to try.
initialise.
110
Enter first value.
repeat
{
process value.
enter a value.
}
until value is negative.
111
for i taking values from 1 to n do
{
output i and i squared.
take a new line.
}
It is normal in the forms ‘repeat n times’ and ‘for i taking values from start
to finish’ to not execute the body of the loop if n is zero or if the start value
is greater than the finish value.
The most basic of repetition control structures is the while control struc-
ture since all the others can be simulated by it. However the others are
useful in some cases, particularly the for control structure. They all have
equivalents in C++.
15.5 Summary
• An important facility in designing algorithms is the ability to specify
the repetition of a group of operations.
• The most basic repetition control structure is the while loop. This
loop repeats the body of a loop while some condition remains true. If
the condition is initially false then the loop body is never executed.
• The for repetition control structure repeats the body of the loop a
fixed number of times, possibly while some control variable sequences
through a specified set of values.
112
increment i.
}
output sum.
What would be output if the value entered for n was 0? What would
be the effect of reversing the order of the statements in the loop body
on the general result produced by the algorithm?
15.7 Exercises
1. In example 2 in this lesson an algorithm was produced to process
examination marks. Extend the algorithm so that an indication of
pass or fail is printed for each student. A student passes if his/her
average mark over the two subjects is greater than 40 and neither
mark is below 35. Also extend the algorithm so that it will output a
suitable message if no student details are entered.
Use a sentinel controlled loop and choose a suitable value for the sen-
tinel.
3. Rewrite your solution to Exercise 1 for the case where the number of
students in the class is entered initially. Write one version using a
while loop and another using a repeat loop.
113
Lesson 16
114
loop. Otherwise there would be no way of changing the truth value
of the condition, which would mean that the loop would become an
infinite loop once it had been entered. In the above example x was
given a new value inside the body of the while statement by entering
the next value from the user.
int i;
i = 1;
while (i <= 10)
{
cout << i << endl;
i++;
}
nl while.cpp
115
sumnat 1.cpp
1. The condition i <= n requires that i and n must have values before
the while loop is executed. Hence the initialisation of i to 1 and
the entry of a value for n before the while statement.
2. It is possible that a while loop may not be executed at all. For example
if the user entered a value 0 for n then the condition i <= n would be
false initially and the statement part of the while loop would never
be entered.
i = 0;
while (i < n)
{
i = i + 1;
sum = sum + i;
}
// IEA Oct. 95
// Tabulates x and sin(x)
#include <iostream.h>
#include <math.h> // because we are going to use
116
// a mathematical function
void main()
{
const float degtorad = M_PI/180; // convert degrees
// to radians
int degree = 0; // initialise degrees to zero
float radian; // radian equivalent of degree
// Output headings
cout << endl << "Degrees" << " sin(degrees)"
<< endl;
// Now loop
while (degree <= 90)
{
radian = degree * degtorad; // convert degrees to
// radians
cout << endl << " " << degree << " "
<< sin(radian);
degree = degree + 5; // increment degrees
}
cout << endl;
}
sin 2.cpp
117
set sum to zero.
set count to zero.
enter first value.
set minimum and maximum to this value.
while (value is positive)
{
add value to sum.
add one to count.
if value is bigger than maximum then
set maximum to value.
if value is smaller than minimum then
set minimum to value.
read a value.
}
if count is zero
then output ‘no data entry’
else {
set average to sum/count.
output count, average, maximum and minimum.
}
The above algorithm can be written in C++ as follows:
// IEA Aug 96
// Reads in positive data until a negative number
// is entered and calculates the average and the
// maximum and minimum of the positive entries.
#include <iostream.h>
void main()
{
float value, sum;
float average, minimum, maximum;
int count;
// initialise
sum = 0.0;
count = 0;
cout << "Enter a value: ";
cin >> value;
minimum = value;
maximum = value;
while (value >= 0.0)
{
// process value
118
sum += value;
count++;
if (value > maximum)
maximum = value;
else if (value < minimum)
minimum = value;
// get next value
cout << "Enter a value: ";
cin >> value;
}
if (count == 0)
cout << "No data entry" << endl;
else
{
average = sum / count;
cout << "There were " << count << " numbers" << endl;
cout << "Average was " << average << endl;
cout << "Minimum was " << minimum << endl;
cout << "Maximum was " << maximum << endl;
}
}
maxminav.cpp
A program is required which will read in the marks as above for each
student and will output for each student, in one line, the above information
together with a final mark for each subject. The final mark in each subject
is 70% of the examination mark plus 30% of the coursework mark. The
average final mark for each subject should also be output. End of input is
to be signalled by input of a negative candidate number. A first algorithmic
description of the required program is:
initialise.
119
enter candidate number.
while candidate number is positive
{
enter marks for candidate.
process marks.
output results for candidate.
enter candidate number.
}
calculate subject averages.
output subject averages.
This is then easily translated into the following program - the main
function only is listed.
void main()
{
int candno; // candidate number
int s1, cw1, s2, cw2; // candidate marks
int final1, final2; // final subject marks
120
int count; // number of students
int sum1, sum2; // sum accumulators
int subav1, subav2; // subject averages
const float EXAMPC = 0.7, // mark weightings
CWPC = 0.3;
// initialise
sum1 = 0;
sum2 = 0;
count = 0;
// enter candidate number
cout << "Input candidate number: ";
cin >> candno;
while (candno >= 0)
{
// enter marks
cout << "Input candidate marks: ";
cin >> s1 >> cw1 >> s2 >> cw2;
// process marks
count++;
final1 = int(EXAMPC*s1 + CWPC*cw1);
final2 = int(EXAMPC*s2 + CWPC*cw2);
sum1 += final1;
sum2 += final2;
// output candidate number and marks
cout << candno << " "
<< s1 << " " << cw1 << " "
<< s2 << " " << cw2 << " "
<< final1 << " " << final2
<< endl;
// enter next candidate number
cout << "Input candidate number (negative to finish): ";
cin >> candno;
}
// evaluate averages
subav1 = sum1/count;
subav2 = sum2/count;
// output averages
cout << endl << "Subject1 average is " << subav1
<< endl << "Subject2 average is " << subav2
<< endl;
}
exam 1.cpp
121
Note that this program would fail if the first candidate number entered
was negative. The statement loop in the while statement would not be
executed and hence count would retain its initial value of zero. This would
lead to a division by zero when an attempt was made to calculate the aver-
ages. It is often difficult to decide whether a program should cope gracefully
with non-existent data, after all why would a user use the program if they
had no data to enter? However a typing error may lead to the entry of un-
suitable data and it is preferable that the program should recover gracefully
from this situation rather than fail with an obscure run-time error later.
This program could do this by either checking the sign of the first candidate
number entered and terminating with a suitable message if it is negative
or could recognise the situation by checking that count is non-zero before
proceeding to calculate the average.
This program could be extended by adding various facilities to it, for
example indicating for each student whether they have passed judged by
some criteria. See the exercises for possible extensions for you to try.
122
old new
3 (3 + 10/3)/2 → 3.17
3.17 (3.17 + 10/3.17)/2 → 3.1623
3.1623 (3.1623 + 10/3.1623)/2 → 3.162278
It can be seen that the sequence of approximations is rapidly converging
to the correct value, which is 3.16227766. This may not always be true in
every application of iterative methods, but in the case of square roots it will
always happen as long as the first approximation chosen is positive.
In the algorithmic description above the phrase ‘while old_app and
new_app are not close enough’ was used. How do we test this? In the
square root example it might be decided that the new approximation would
be accepted as the correct value of the root when it differed by less than
0.0005 from the previous approximation. This would mean that the esti-
mate of the root was correct to three decimal places. It might be tempting
to write the test as
but in the second iteration this test would give 3.1623-3.17 > 0.0005
which is equivalent to -0.0077 > 0.0005 which is false, causing the itera-
tion process would stop prematurely. The problem is that if new_app-old_app
is ever negative then since a negative number can never be greater than a
positive number the condition will become false however large the difference
between new_app and old_app! The solution to this problem is to test the
absolute magnitude, without regard to sign, of new_app and old_app. C++
has a function fabs(x) which returns the absolute value of x i.e. x if x is
positive and -x if x is negative. Using this function the test could be written:
which solves the problem above. In general if trying to find if two quantities
are within some tolerance of each other then test the absolute value
of the difference between them against the tolerance. However there is
another difficulty with the above. Consider the following approximations:
exact value approximation
100 100.1
0.1 0.2
Which of these approximations is the most accurate? They both have
an absolute error of 0.1 but in one case the error is 0.1% of the quantity
being approximated and in the other it is 100% of the quantity being ap-
proximated. Thus if these approximations were used as a multiplying factor
in the next stage of a computation then in one case the answer would be a
123
small fraction larger than it should be whereas in the other case the answer
would be twice what it should be! Thus the relative size of the error with
respect to the quantity being approximated is important. In the square root
problem if x was 0.000001, with square root 0.001, then two successive ap-
proximations 0.0015 and 0.00108 would have a difference less than 0.0005
and hence 0.00108 would be accepted as a result. However this result would
be 8% in error. Hence it is always safer to test the relative error against the
tolerance, this ensures that results of different sizes have the same number
of significant figures correct. Hence if three significant figures were required
in the result the test should be:
Since the square root of a negative number is not defined (in real arith-
metic) no attempt should be made to use this algorithm if the value input
is negative. Also if the input is zero, which has square root zero, the use of
this algorithm will lead to a division by something approaching zero. This
should be avoided by making zero a special case. Hence the program:
void main()
{
const float tol = 0.000005; // relative error tolerance
float value;
float old_app, new_app;
cout << "Square root of a number"
<< endl << endl;
cout << "Enter a positive number: ";
cin >> value;
if (value < 0.0)
cout << "Cannot find square root of negative number"
<< endl;
else
if (value == 0.0)
cout << "square root of "
<< value
<< " is 0.0"
<< endl;
else
{
old_app = value; // take value as first approximation
new_app = (old_app + value/old_app)/2;
while (fabs((new_app-old_app)/new_app) > tol)
{
old_app = new_app;
new_app = (old_app + value/old_app)/2;
124
}
cout << "square root of "
<< value
<< " is " << new_app
<< endl;
}
}
sqrt.cpp
16.7 Summary
• The while statement in C++ allows the body of a loop to be exe-
cuted repeatedly until a condition is not satisfied. For as long as the
condition is true the loop body is executed.
n = 10;
i = 0;
while ( i < n ) {
...
i++;
}
(a) 9
(b) 10
125
(c) 11
2. What are the first and last values of i output by this loop?
n = 10;
i = 0;
while ( ++i < n ) {
cout << i << endl;
}
(a) 1 and 9
(b) 0 and 9
(c) 0 and 10
(d) 1 and 10
3. What are the first and last values of i output by this loop?
n = 10;
i = 0;
while ( i++ < n ) {
cout << i << endl;
}
(a) 1 and 10
(b) 0 and 10
(c) 1 and 9
(d) 0 and 9
int fact, i;
fact = 1;
i = 2;
while (i <= 6)
fact *= i;
i++;
cout << fact;
126
int i;
while (i < 10)
{
cout << i << endl;
i++;
}
16.10 Exercises
1. In exercise 2 of Lesson 15 you should have developed an algorithm for
the following problem:
127
variables to take values up to a 10 digit integer. It is important while
programming to remember that there are limitations on the size and
precision that numerical values can take, if these limitations are not
kept in mind nonsensical results can be produced.
#include <stdlib.h>
#include <time.h>
#include <iostream.h>
void main()
{
int r; // random integer;
int i = 0; // control variable
srand(time(0)); // initialise random number generator
while (i < 10)
{
r = rand(); // gets random int in 0-RAND_MAX
cout << "Random integer was " << r;
i++;
}
}
Note that the function srand is used once at the beginning of main,
this ensures that the random number sequence will start at a different
value each time that the program is run. If the call of srand was left
out then the program would deliver exactly the same results each time
it was run, not very random! The function rand() returns a random
integer in the range 0 to RAND_MAX. RAND_MAX is a const int defined
in the include file stdlib.h. The use of time(0) as an argument to
srand ensures that a new starting value is used each time the program
is run. Note that the inclusion of the files stdlib.h and time.h is
required before these functions can be used.
Now extend the above program so that it generates n random numbers,
where n is entered by the user, and counts how many of the random
integers generated are less than a half of RAND_MAX. If the random
number generator is producing a uniform spread of random numbers
in the interval then this should converge towards a half of n. Execute
your program with increasing values of n (but not bigger than 32767).
128
Lesson 17
129
once, unlike the while statement where the body of the loop is not exe-
cuted at all if the condition is initially false. The statement may be a single
statement or a compound statement. The effect of a do-while statement
can always be simulated by a while statement so it is not strictly neces-
sary. However in some situations it can be more convenient than a while
statement.
sumnat 2.cpp
If the user entered a value of 0 for n then the value of 1 would be returned
as the value of sum. This is obviously incorrect and, as noted above, is
because the loop statement of a do-while loop is always executed at least
once. In this case if the entered value of n is zero then the loop statement
should not be entered at all! Thus if there is any possibility that some valid
data may require that a loop be executed zero times then a while statement
should be used rather than a do-while statement.
130
float low, high; // bounds for x
valid.cpp
Note the use of the logical operator not (!) operating on the boolean
value, to invert its truth value.
Another way of controlling the loop is to assign the value of the condition
directly to accept. At first sight, this may appear strange, but the condition
is already being evaluated as either true or false, so it makes sense to
replace the if-else statement with
accept = low <= x && x <= high;
131
<< s1 << " " << cw1 << " "
<< s2 << " " << cw2 << " "
<< final1 << " " << final2
<< endl;
// enter candidate number
cout << "Input candidate number (negative to finish): ";
cin >> candno;
} while (candno >= 0);
exam 2.cpp
17.4 Summary
• The do-while loop statement will always be executed at least once
since the condition is not tested until after the first execution of the
loop statement.
n = 10;
i = 0;
do {
...
i++;
} while ( i < n );
(a) 9
(b) 10
(c) 11
2. What are the first and last values of i output by this loop?
n = 10;
i = 0;
do {
132
cout << i << endl;
} while ( ++i < n );
(a) 1 and 9
(b) 0 and 9
(c) 0 and 10
(d) 1 and 10
3. What are the first and last values of i output by this loop?
n = 10;
i = 0;
do {
cout << i << endl;
} while ( i++ < n );
(a) 1 and 10
(b) 0 and 10
(c) 1 and 9
(d) 0 and 9
int i;
i = -12;
do
{
cout << i << endl;
i = i - 1;
}
while (i > 0)
133
17.7 Exercises
1. Rewrite the program that you produced for exercise 1 in Lesson 16
using a do-while statement rather than a while statement.
134
Lesson 18
135
is executed followed by the update statement. The cycle of (test;execute-
statement;update) is then continued until the test expression evaluates to
false, control then passes to the next statement in the program.
nl for.cpp
int i;
float x;
for (i = 0; i <= 16; i++)
{
x = 0.1 * i;
cout << x << " " << sin(x) << endl;
}
sin 3.cpp
Note how an integer variable i is used to control the loop while inside the
loop the corresponding value of x is calculated as a function of i. This is
preferable to the following:
float x;
for (x = 0.0; x <= 1.6; x += 0.1)
cout << x << " " << sin(x) << endl;
136
The problem with the above is that floating point variables are not held
exactly, thus 0.1 might be represented by something slightly larger than 0.1.
Then after continually adding 0.1 to x the final value that should be 1.6
may actually be something like 1.60001. Thus the test x <= 1.6 would fail
prematurely and the last line of the table would not be printed. This could
be corrected by making the test x <= 1.605 say.
In general it is probably best to use integer variables as control variables
in for loops.
137
sum2 = sum2+final2;
// output marks
cout << candno << " "
<< s1 << " " << cw1 << " "
<< s2 << " " << cw2 << " "
<< final1 << " " << final2
<< endl;
}
// evaluate averages
subav1 = sum1/count;
subav2 = sum2/count;
// output averages
cout << endl << "Subject1 average is " << subav1
<< endl << "Subject2 average is " << subav2
<< endl;
}
exam 3.cpp
a = m2 − n2
b = 2mn
c = m 2 + n2
138
{
for each value of n from 1 to m-1 do
{
evaluate and print a triple.
}
}
This description uses a for loop, a looping construct that repeats the
loop statement as some control variable takes a sequence of values. Also
note that one for loop is nested inside another, this is very common. From
this description the following C++ program is easily produced:
void main()
{
int max, // maximum value of m to be used
m, n, // control variables for loops
t1, t2, t3; // pythagorean triple
// enter and validate max
do {
cout << "Enter a maximum value for m ( >1 ): ";
cin >> max;
}
while (max < 2);
// loop on m from 2 to max
for (m=2; m <= max; m++)
{
// now loop on n from 1 to m-1
for (n=1; n < m; n++)
{
// evaluate and print triple
t1 = m*m-n*n;
t2 = 2*m*n;
t3 = m*m+n*n;
cout << t1
<< " " << t2
<< " " << t3
<< endl;
}
}
}
pyth 2.cpp
139
18.5 Summary
• The for statement is is used to implement loops which execute a fixed
number of times. This number of times must be known before the for
statement is entered.
• If the test expression in a for statement is initially false then the loop
statement will not be executed. Thus a for statement may iterate zero
or more times.
n = 100;
for ( i = 0; i < n; i++ ) {
...
}
(a) 99
(b) 100
(c) 101
2. What are the first and last values of i output by this loop?
n = 20;
for ( i = 0; i < n; i++ ) {
cout << i << endl;
}
(a) 0 and 19
(b) 1 and 19
(c) 0 and 20
(d) 1 and 20
3. What are the first and last values of i output by this loop?
n = 15;
i = 0;
for( i = 0; i <= n; i++ ) {
cout << i << endl;
}
(a) 0 and 15
140
(b) 1 and 14
(c) 1 and 15
n = 27;
i = 0;
for( i = 0; i <= n; i+= 2 ) {
cout << i << endl;
}
(a) 25
(b) 28
(c) 27
(d) 26
int i;
for ( i = 1; i <= 12; i *= 2 )
cout << i << endl;
int i;
for (i=1; i<20; i = i+3)
cout << i << endl;
What would happen if the i+3 in the update expression was changed
to i-3?
141
18.8 Exercises
1. Write an algorithm for a program to produce the sum of the series
1 1 1 1
1+ + + + ··· +
2 3 4 n
where n is entered by the user. Then write and test the program.
Change your algorithm so that the sum of the series
1 1 1 1
1− + − + ···
3 5 7 n
is computed. Then write and test the program. As n gets larger the
results should tend towards 0.7854 (π/4).
2. In exercise 1 of Lesson 16 you wrote a program to enter a set of numbers
and to output counts of the number of negative and positive numbers.
Change that program so that it asks the user how many numbers are
to be entered and uses a for loop.
3. In exercise 3 of Lesson 16 it was described how random integers could
be generated by the rand function. This routine can also be used to
generate random fractions in the range 0-1. Since rand() generates
an integer between 0 and RAND_MAX-1 then rand()/float(RAND_MAX)
generates a fraction in the range (0,1). If x is a random number in
the range (0,1) then 1 − 2x is a random fraction in the range (-1,+1).
Start by writing a program that produces n (entered by user) pairs of
random fractions in the range (-1,+1). Use a for loop to implement
the loop.
Once this is working extend your program as follows. Treat each pair
of random values as the co-ordinates of a point (x, y) and output a
count of how many of the generated points lie inside a circle of radius
1 and centre at (0,0) i.e. x2 + y 2 < 1.
If the random number generator used is reasonably uniform in its
distribution of numbers then the probability that a point lands in the
circle is the ratio of the area of the circle to the area of the 2 × 2
square centred on the origin. This ratio is π/4. Thus an estimate of
the value of π can be made from the ratio of the count of points inside
the circle to the total number of points. Hence extend your program
to output an estimate of π. This is known as a Monte Carlo method.
Run your program a few times with increasing values of n to see how
the estimate of π improves with the number of trials carried out.
4. Write an algorithm to produce an n times multiplication table ( n less
than or equal to 10). For example, if n is equal to four the table should
appear as follows:
142
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
Convert your algorithm into a program. Use nested for loops and pay
attention to formatting your output so that it is displayed neatly.
143
Lesson 19
So far all input and output has been done by obtaining data from the input
stream cin and sending output to the output stream cout. These streams
have been connected to the keyboard and screen respectively. There are
many situations when these facilities are not sufficient. For example:
1. When the amount of data to be entered to a program is very large or
when a program is to be executed at a later date with the same data.
This may happen while developing and testing a program with a set
of test data.
2. When the data for a program has been produced by another computer
program.
3. When a permanent record of the output of a program is required.
In all these cases External Files are required. Thus if a program re-
quires a significant amount of data to be entered then the data can be
entered on a file using a text editor and this file used as the input medium
while developing and testing the program. Similarly output can be sent to
a file so that a permanent record of results is obtained.
19.1 Streams
In C++ data is written to and from streams. A stream is :
• a sequence of characters
• connected to a device or to a (disk) file
• referred to by name
The streams cin and cout which are connected to the keyboard and the
screen respectively have already been considered. When using these streams
the file iostream.h must be included in the program.
144
C++ allows other streams to be set up. These streams must be declared
just as identifiers are declared. Thus streams that are to be used for input
are declared as having the type ifstream and those that are used for output
are declared as having the type ofstream. Once a stream has been declared
it must be connected to an external file.
If streams are going to be used the file fstream.h must be included in
the program.
To connect these streams to the appropriate external files the open func-
tion is used. The open function is a member function of the stream class
and to connect the stream ins to a file indata.dat the following statement
is used:
ins.open("indata.dat");
The general form for a stream with identifier streamname and a file with
name filename is:
streamname.open(filename);
If the file indata.dat did not exist or could not be found then this
open function will fail. Failure of the open function is tested by using the
the function streamname.fail() which returns true if the open function
failed. When using the open function failure should always be tested for as
in the following example:
ifstream ins;
ins.open("indata.dat");
if (ins.fail())
{
cout << "Error opening file indata.dat"
<< endl;
return 1;
}
In this example it is assumed that the failure occurs within the main()
program. This means that the return statement exits the main program
145
and hence the program is terminated. The value 1 that is returned indicates
to the operating system that the program has terminated with an error
condition. As the main program now returns a value it must be declared as
having the type int rather than void.
Having connected the external files to the streams any input/output
from/to these streams will then be from/to the connected files.
In the following example two streams are declared, one for input called
ins and another for output called outs. These streams are then connected
to files with names indata.dat and results.dat respectively by:
int main()
{
ifstream ins;
ofstream outs;
ins.open("indata.dat");
if (ins.fail())
{
cout << "Error opening indata.dat"
<< endl;
return 1;
}
outs.open("results.dat");
if (outs.fail())
{
cout << "Error opening results.dat"
<< endl;
return 1;
}
.
.
All access to these files now uses the declared stream names ins and outs
and the input/output operators << and >>. Input/output manipulators can
also be used on the output stream.
Thus a data item is entered from the stream ins by:
ins >> x;
and results are output to the stream outs by:
outs << "Result is " << setw(6) << count << endl;
146
of-file condition, eof. This condition is set true when an an attempt is made
to read beyond the end of a file, otherwise it is set to false. Unlike some other
languages the end-of-file character is actually entered and the eof function
returns true when it is entered. For example to read values from a file and
evaluate their average then the following code could be used:
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
int main()
{
int n;
float x, sum, average;
ifstream ins; // input stream
ofstream outs; // output stream
ins.open("indata.dat");
147
average = sum / n;
cout << "Writing results to file " << endl;
outs << "The average of " << n << " numbers is "
<< setprecision(2)
<< average << endl;
ins.close(); // Close all files - GOOD PRACTICE
outs.close();
return 0; // indicate success
}
sumfile.cpp
Note that at the end the streams ins and outs were closed. While some
operating systems will do this automatically when your program terminates
it is good practice to always close files before exiting a program. If this is
not done then sometimes not all of the output is written to the file.
If the program was to be run again with data from a different file then
the only way this could be done would be to edit the program above and
replace each occurrence of indata.dat with the name of the other input
file. This is obviously inconvenient and it is much better to allow the user to
enter the file name at run-time. However this topic is delayed until Lesson 23
when further consideration has been given to the representation of arbitrary
strings within a program.
19.4 Summary
• To send data to/from an external file the file must be connected to a
stream.
• If streams other than the standard input streams cin and cout are
used then the file fstream.h must be included in the program.
148
19.5 Review Questions
1. What is the purpose of the open function of a stream?
19.6 Exercises
1. In question 2 of Lesson 18 you wrote a program which input a series
of numbers and output counts of the number of positive and negative
numbers. Amend this program so that it takes data from a file (make
up a sample file) and terminates on the end of file condition. Write
the output from the program to another file.
149
Lesson 20
In Lesson 5 a program was produced which entered the hours worked and
an hourly rate of pay for an employee and output the employee’s total wage.
This could be expanded so that a user could enter this data for several
employees in turn and get their wages output. A suitable algorithmic de-
scription for such a program might be:
repeat
enter hours worked and hourly rate.
produce wage.
prompt user ‘any more data?’
read reply
until reply is no
Since an algorithm has already been produced which outputs the wage
given the hours worked and the hourly rate the description of this could
now be used as the expansion of produce wage. This re-use of an algorithm
from a previous program saves time in developing an algorithm again and
if the algorithm has been previously tested and verified to be correct also
reduces the chances of error. The best mechanism for this re-use of an
algorithm is to incorporate it into a function. The function is given a name
and is supplied with the input parameters (or arguments) of the problem
and returns the results as output parameters. Thus the description for the
calculation of the wage could be placed in a function called, say, calcwage.
This function would take the hours worked and the hourly rate as input
parameters and would return the wage as output. This function is then
called to produce the wage when values are available for the hours worked
and the hourly rate. The algorithm above could then be written:
repeat
Enter hours worked and hourly rate.
150
Call the function calcwage(hours,rate,wage).
print out wage.
prompt user ‘any more data?’
read reply.
until reply is no.
Apart from its use in this program the function calcwage might possibly
be used in other programs in the future which required the calculation of
wages. Another advantage of the above approach is that if the rules for
calculating wages are changed then only the function calcwage need be
changed. Thus if the solution of a problem has been neatly encapsulated into
a function which has been comprehensively tested and debugged then it can
be incorporated into subsequent programs. This obviously saves much work
and removes some sources of error. Ultimately everyone in an organisation
could use this function in their programs without even having to understand
how to actually solve the problem themselves.
151
different programs. This obviously saves much work and cuts down
errors if such functions have already been well tested.
3. There are many very specialised problem areas, not every program-
mer can know every area. For example many programmers working in
scientific applications will frequently use mathematical function rou-
tines like sine and cosine, but would have no idea how to write such
routines. Similarly a programmer working in commercial applications
might know very little about how an efficient sorting routine can be
implemented. However a specialist can write such routines, place them
in a public library of functions and all programmers can benefit from
this expertise by being able to use these efficient and well tested func-
tions.
Before looking at how functions are implemented in C++ the use of the
mathematical function routines supplied in C++ is considered.
cout << endl << " " << degree << " "
<< sin(radian);
152
acos(x) inverse cosine, -1 ≤ x ≤ +1, returns value
in radians in range 0 to π
asin(x) inverse sine, -1 ≤ x ≤ +1, returns value
in radians in range 0 to π
atan(x) inverse tangent, returns value in radians
in range -π/2 to π/2
cos(x) returns cosine of x, x in radians
sin(x) returns sine of x, x in radians
tan(x) returns tangent of x, x in radians
exp(x) exponential function, e to power x
log(x) natural log of x (base e), x > 0
sqrt(x) square root of x, x ≥ 0
fabs(x) absolute value of x
floor(x) largest integer not greater than x
ceil(x) smallest integer not less than x
In all these functions the parameter x is a floating point value. The x is
used as a formal parameter, that is it is used to denote that a parameter
is required and to allow the effect of the function to be described. When
the function is called then this formal parameter is replaced by an actual
parameter. The actual parameter can be a constant, a variable or an
expression. An expression may include a call of another function.
These functions are called by quoting their name followed by the ac-
tual parameter enclosed in rounded brackets, for example, exp(x+1). The
function call can then be used anywhere in an expression that an ordinary
variable may be used. Hence the following examples:
y = sin(3.14159);
z = cos(a) + sin(a);
factor = sin(theta)/(sin(delta) - sin(delta-theta));
theta = acos(1.0/sqrt(1 - x*x));
if (sin(x) > 0.7071)
cout << "Angle is greater than 45 degrees";
cout << "The value is " << exp(-a*t)*sin(a*t);
The file math.h must be included in any program that is going to use
any functions from this library. math.h also defines some constants which
may be used. For example M_PI can be used for π and M_E can be used for
e.
20.3 Summary
• The top-down approach to program design splits the initial problem
into several sub-problems which in turn can be further sub-divided.
Once a sub-problem is simple enough to solve then it can be imple-
mented as a function.
153
• A function should be completely self-contained. That is it should com-
municate with the calling program only via supplied input parameters
and output parameters. The user of a function should not have to
know any details of how the function is implemented.
20.5 Exercises
1. Each competitor in a race is started separately. The start and finish
time for each competitor is noted in hours, minutes and seconds. The
number of competitors is available as is the distance of the race in
miles. Design an algorithm which will initially enter the number of
competitors and the distance of the race and will then enter for each
competitor a competitor number together with the competitor’s start
and finish times. The competitor’s elapsed time should then be output
in minutes and seconds together with the average speed in miles per
hour. It is desirable that the start and finish times should be validated
as being legal times in the twenty four hour clock. In designing your
algorithm identify at the initial stage which tasks could be carried
out by using functions. Do not expand the functions any further but
specify what they should do and also specify their input parameters
and output parameters.
154
Lesson 21
Introduction to User-defined
functions in C++
C++ allows programmers to define their own functions. For example the
following is a definition of a function which given the co-ordinates of a point
(x,y) will return its distance from the origin.
float distance(float x, float y)
// Returns the distance of (x, y) from origin
{
float dist; //local variable
dist = sqrt(x * x + y * y);
return dist;
}
dist.cpp
This function has two input parameters, real values x and y, and returns
the distance of the point (x,y) from the origin. In the function a local
variable dist is used to temporarily hold the calculated value inside the
function.
The general form of a function definition in C++ is as follows:
function-type function-name( parameter-list )
{
local-definitions;
function-implementation;
}
• If the function returns a value then the type of that value must be
specified in function-type. For the moment this could be int, float
or char. If the function does not return a value then the function-type
must be void.
155
• The function-name follows the same rules of composition as identifiers.
void skipthree(void)
// skips three lines on output
{
cout << endl << endl << endl;
}
skip3.cpp
Note that the function-type has been given as void, this tells the compiler
that this function does not return any value. Because the function does not
take any parameters the parameter-list is empty, this is indicated by the
void parameter-list. No local variables are required by this function and the
function implementation only requires the sending of three successive end of
line characters to the output stream cout. Note the introductory comment
that describes what the function does. All functions should include this
information as minimal comment.
Since this function does not return a value it cannot be used in an ex-
pression and is called by treating it as a statement as follows:
skipthree();
Even though there are no parameters the empty parameter list () must be
inserted.
When a function is called the C++ compiler must insert appropriate
instructions into the object code to arrange to pass the actual parameter
values to the function code and to obtain any values returned by the func-
tion. To do this correctly the compiler must know the types of all parameters
156
and the type of any return value. Thus before processing the call of a func-
tion it must already know how the function is defined. This can be done by
defining any functions that are used in the main program before the main
program, for example the function skipthree could be incorporated in a
program as follows:
#include <iostream.h>
void skipthree(void)
// Function to skip three lines
{
cout << endl << endl << endl;
}
void main()
{
int ....;
float ....;
cout << "Title Line 1";
skipthree();
cout << "Title Line 2";
.
.
}
However this has disadvantages, namely:
• The main program tends to convey much more information of use
in understanding the program than do individual functions. So it is
better if the main program comes first. However this means that the
compiler meets the call of a function before it meets the definition of
the function.
157
void skipthree(void);
#include <iostream.h>
void main()
{
int ....;
float ....;
cout << "Title Line 1";
skipthree();
cout << "Title Line 2";
.
.
}
skip3.cpp
In fact when using functions from the stream libraries and the mathe-
matical libraries prototypes are required for these functions. This is handled
by including the files iostream.h and math.h which, among other things,
contain the function prototypes.
void skip(int n)
158
// Function skips n lines on output
{
int i; // a local variable to this function
// now loop n times
for (i = 0; i < n; i++)
cout << endl;
}
skipn.cpp
void main()
{
int m = 6, n = 3;
...............;
skip(m);
.......;
skip(m + n);
............;
skip(4);
.......;
}
skip (4.0);
would not be acceptable because the actual parameter type must match
the formal parameter type given in the definition of the function.
159
In writing the function prototype for a function with parameters it is not
necessary to detail the formal names given to the parameters of the function,
only their types. Thus a suitable function prototype for the parameterised
version of skip would be:
dist.cpp
• The function has been given the type float because it is going to
return a float value.
• A local variable dist has been declared to temporarily hold the cal-
culated distance.
160
return sqrt(x*x + y*y);
When the function is called the formal parameters x and y are replaced
by actual parameters of type float and in the same order, i.e. the x co-
ordinate first. Since the function returns a value it can only be used in an
expression.
Hence the following examples of the use of the above function in a pro-
gram in which it is declared:
float a, b, c, d, x, y;
a = 3.0;
b = 4.4;
c = 5.1;
d = 2.6;
x = distance(a, b);
y = distance(c, d);
float mysqrt(float x)
// Function returns square root of x.
// If x is negative it returns zero.
{
const float tol = 1.0e-7; // 7 significant figures
float xold, xnew; // local variables
if (x <= 0.0)
return 0.0; // covers -ve and zero case
else
{
xold = x; // x as first approx
xnew = 0.5 * (xold + x / xold); // better approx
while (fabs((xold-xnew)/xnew) > tol)
{
xold = xnew;
xnew = 0.5 * (xold + x / xold);
}
return xnew; // must return float value
}
} // end mysqrt
161
mysqrt.cpp
If the function has type void then it must not return a value. If a void
function does return a value then most compilers will issue some form of
warning message that a return value is not expected.
return sum;
} // End of sumsq
sumsq.cpp
float sumsquare;
int number;
cout << "Enter number (>= 0): ";
cin >> number;
sumsquare = sumsq(number);
162
if ( n == 0)
return 1.0;
else
{
absn = int(fabs(n));
for (i = 1; i <= absn; i++)
product *= x;
if (n < 0)
return 1.0 / product;
else
return product;
}
} // end of power
power.cpp
float x, y;
int p;
cout << "Enter a float and an integer: ";
cin >> x >> p;
y = power(x, p);
y = power(x + y, 3);
functest.cpp
n++;
just before the final closing } and the following statements are executed:
p = 4;
y = power(x, p);
cout << p;
What would be printed out for the value of p? In fact instead of the value
5 that you might expect p would still have the value 4. This is because the
parameter has been passed by value. This means that when the function is
called a copy of the value of the actual parameter used in the call is passed
across to the memory space of the function. Anything that happens inside
the function to this copy of the value of the parameter cannot affect the
163
original actual parameter. All the examples that have been considered have
used call-by-value parameters. This is because all the parameters used have
been input parameters. To make a parameter call-by-value it is specified in
the parameter list by giving its type followed by its name.
Thus if a parameter is only to be used for passing information into a
function and does not have to be returned or passed back from the function
then the formal parameter representing that parameter should be call-by-
value. Note also that since the function cannot change the value of a call-
by-value parameter in the calling program strange side effects of calling a
function are avoided.
21.7 Summary
• A C++ function can return a value. The function must be declared
to have the same type as this value. If the function does not return a
value then it must be given the type void.
void example(int n)
{
int i;
for (i=0; i<n; i++)
164
cout << ’*’;
cout << endl;
}
How would you call this function in a program? How would you use
this function in producing the following output on the screen?
*
**
***
****
a)
void change(void)
{
int x;
x = 1;
}
void main()
{
int x;
x = 0;
change();
cout << x << endl;
}
b)
void change(int x)
{
x = 1;
}
void main()
{
int x;
x = 0;
change(x);
cout << x << endl;
}
165
5. Write a function prototype for a function that takes two parameters
of type int and returns true if these two integers are a valid value for
a sum of money in pounds and pence. If not valid then false should
be returned.
6. A function named ex1 has a local variable named i and another func-
tion ex2 has a local variable named i. These two functions are used
together with a main program which has a variable named i. Assum-
ing that there are no other errors in the program will this program
compile correctly? Will it execute correctly without any run-time er-
rors?
21.9 Exercises
1. Write a function which draws a line of n asterisks, n being passed as a
parameter to the function. Write a driver program (a program that
calls and tests the function) which uses the function to output an m×
n block of asterisks, m and n entered by the user.
166
Lesson 22
Further User-defined
functions in C++
167
// If the roots are real then the roots are
// returned in two parameters root1 and root2 and
// the function returns true, if they are complex
// then the function returns false.
{
float disc; // local variable
disc = b * b - 4 * a * c;
if (disc < 0.0)
return false;
else
{
root1 = (-b + sqrt(disc))/(2 * a);
root2 = (-b - sqrt(disc))/(2 * a);
return true;
}
}
quadrat.cpp
Note that the roots, which are output parameters, have been declared
to be reference parameters, while the coefficients are input parameters and
hence are declared to be value parameters. The function prototype would
have the following form:
int quadsolve(float, float, float, float&, float&);
This might be called in a program as follows:
float c1, c2, c3;
float r1, r2;
.
.
if (quadsolve(c1, c2, c3, r1, r2))
cout << "Roots are " << r1 << " and " << r2 << endl;
else
cout << "Complex Roots" << endl;
quadrat.cpp
168
Note how the return value has been used to discriminate between the
situation where the roots are real and are found in the two output parameters
and the case where the roots are complex and no values for the roots are
returned.
3
161432 5 6 50
543289 10 2 25
876234 2 10 75
indicating that there are three items on the invoice, the first item having an
item code of 161432, an order quantity of 5 and a unit price of six pounds
fifty pence. Assume that the days date will also be entered.
Write a C++ program to enter details of such an invoice and to output
an invoice which indicates the total cost of each item and the total cost of
the invoice together with full details. The above details might produce an
invoice as follows:
Total 76.50
initialise.
enter date.
enter number of items into n.
output headings.
for n items do
169
{
enter a record.
calculate total cost of item.
accumulate total invoice cost.
write line of invoice.
}
output total cost.
Assume that there are four programmers available to implement this
program. There are four major operations inside the for loop hence each
programmer could be given one operation to implement. The best way to
do this is to use a function for each operation. Each programmer can then
be given a precise definition of a function.
For example consider the operation enter a record. This function
must read in the integer quantities item number, quantity and unit price
in pounds and pence. Hence it has no input parameters and four output
parameters. A definition of the function could then be written as follows:
Function name: dataentry
Operation: Enter a record
Description: Enters four integers from the current
input line and returns their values.
Parameters: Output parameter int itemno
Output parameter int quantity
Output parameter int unitpounds
Output parameter int unitpence
Similarly the other functions could be specified as follows:
Function name : calccost
Operation : Calculates the cost for a single item.
Description : Given the unit price of an item in
pounds and pence and the quantity of
the item calculates the total cost in
pounds and pence.
Parameters : Input parameter int quantity
input parameter int unitpounds
input parameter int unitpence
output parameter int totalpound
output parameter int totalpence
170
Parameters : input parameter int totalpound
input parameter int totalpence
input & output parameter int invpound
input & output parameter int invpence
171
calccost(quantity, unitpounds, unitpence, totalpound,
totalpence);
acctotal(totalpound, totalpence, invpound, invpence);
writeline(itemno, quantity, unitpounds, unitpence,
totalpound, totalpence);
}
// write total line
cout << " Total "
<< invpound
<< "."
<< invpence << endl;
}
invoice.cpp
Using the function specifications above the functions can now be written
and tested separately. For example calccost could be written as follows:
{
int p;
p = q * up;
totp = p % 100;
totl = q * ul + p/100;
}
calccost.cpp
// IEA 1996
// Driver program to test calccost
#include <iostream.h>
// function prototype
172
void calccost(int, int, int, int&, int&);
void main()
{
int quant, unitl, unitp, totall, totalp;
// stop on negative quantity
cout << "Enter quantity: ";
cin >> quant;
while (quant >= 0)
{
cout << "Enter unit cost (pounds pence): ";
cin >> unitl >> unitp;
calccost(quant, unitl, unitp, totall, totalp);
cout << endl
<< quant << " times "
<< unitl << " pounds "
<< unitp << " pence "
<< " is "
<< totall << " pounds "
<< totalp << " pence ";
cout << endl << "Enter quantity: ";
cin >> quant;
}
}
calccost.cpp
When testing functions try to use one example of each of the cases
that can occur. For example using the above driver program to show that
calccost works for 7 times 1.10 is not a complete test since it does not
generate any ‘carry’ from the pence to the pounds. An additional test on
say 6 times 1.73 checks that the carry works. Choosing a set of test data to
adequately validate a function requires much thought.
22.3 Summary
• Information is passed back from the function via reference parameters
in the parameter-list. A parameter is declared to be a reference pa-
rameter by appending & to its type. In this case the address of the
actual parameter is passed to the function and the function uses this
address to access the actual parameter value and can change the value.
Hence information can be passed back to the calling program.
173
22.4 Review Questions
1. How is information supplied as input to a function? How can infor-
mation be conveyed back to the calling program?
void change(int& y)
{
y = 1;
}
void main()
{
int x;
x = 0;
change(x);
cout << x << endl;
}
22.5 Exercises
1. Write a function
174
rates of 3, 4, 5,. . . , 10 per cent. Assume that the actual repayment
will be produced by a function which will take as input parameters the
principle P, the repayment time n in years and the rate of interest r
as a percentage rate and will return the monthly repayment in pounds
and pence.
Transform your algorithm into a C++ program. Write a function pro-
totype for the repayment calculation function and write the function
itself as a function stub. That is a function that does not perform
the correct calculation but delivers values that are sufficient to test
the rest of the program. In this case it should return values of zero for
the pounds and pence of the monthly repayment. This will allow you
to test that your program lays the table out properly.
Once you have the table layout working you can now write the function
itself. The repayment each month on a mortgage of P pounds, taken
out over n years at an interest rate of r% is given by:
rP k 12n
repayment =
1200(k 12n − 1)
where
r
k =1+
1200
In writing this function use the function power from Section 21.5. This
means you must add this function, and a suitable prototype, to your
program. Also use the function of exercise 1 above.
175
Lesson 23
Arrays
sum = 0.0;
for (i = 0; i < 6; i++)
{
cin >> x;
sum += x;
}
float a, b, c, d, e, f;
176
and then handling each value individually as follows:
sum = 0;
cin >> a; sum += a;
cin >> b; sum += b;
cin >> c; sum += c;
cin >> d; sum += d;
cin >> e; sum += e;
cin >> f; sum += f;
which is obviously a very tedious way to program. To extend this solution so
that it would work with more than six values then more declarations would
have to be added, extra assignment statements added and the program
re-compiled. If there were 10000 values imagine the tedium of typing the
program (and making up variable names and remembering which is which)!
To get round this difficulty all high-level programming languages use the
concept of a data structure called an Array
177
const int NE = 100;
float annual_temp[NE];
then if more records come to light it is easy to amend the program to cope
with more values by changing the value of NE. This works because the com-
piler knows the value of the constant NE at compile time and can allocate an
appropriate amount of space for the array. It would not work if an ordinary
variable was used for the size in the array declaration since at compile time
the compiler would not know a value for it.
annual_temp[14] = 1.5;
Note that since the first element is at index 0, then the ith element is at
index i-1. Hence in the above the 15th element has index 14.
An array element can be used anywhere an identifier may be used. Here
are some examples assuming the following declarations:
count[i] = count[i] + 5;
count[i] += 5;
178
if (annual_temp[j] < 10.0)
cout << "It was cold this year "
<< endl;
for statements are the usual means of accessing every element in an array.
Here, the first NE elements of the array annual_temp are given values from
the input stream cin.
for (i = 0; i < NE; i++)
cin >> annual_temp[i];
The following code finds the average temperature recorded in the first
ten elements of the array.
sum = 0.0;
for (i = 0; i <10; i++)
sum += annual_temp[i];
av1 = sum / 10;
Notice that it is good practice to use named constants, rather than literal
numbers such as 10. If the program is changed to take the average of the
first 20 entries, then it all too easy to forget to change a 10 to 20. If a const
is used consistently, then changing its value will be all that is necessary.
For example, the following example finds the average of the last k entries
in the array. k could either be a variable, or a declared constant. Observe
that a change in the value of k will still calculate the correct average (pro-
vided k<=NE).
sum = 0.0;
for (i = NE - k; i < NE; i++)
sum += annual_temp[i];
av2 = sum / k;
Important - C++ does not check that the subscript that is used to reference
an array element actually lies in the subscript range of the array. Thus
C++ will allow the assignment of a value to annual_temp[200], however
the effect of this assignment is unpredictable. For example it could lead
to the program attempting to assign a value to a memory element that
is outside the program’s allocated memory space. This would lead to the
program being terminated by the operating system. Alternatively it might
actually access a memory location that is within the allocated memory space
of the program and assign a value to that location, changing the value of
the variable in your program which is actually associated with that memory
location, or overwriting the machine code of your program. Similarly reading
a value from annual_temp[200] might access a value that has not been
set by the program or might be the value of another variable. It is the
programmer’s responsibility to ensure that if an array is declared with n
179
elements then no attempt is made to reference any element with a subscript
outside the range 0 to n-1. Using an index, or subscript, that is out of range
is called Subscript Overflow. Subscript overflow is one of the commonest
causes of erroneous results and can frequently cause very strange and hard
to spot errors in programs.
180
This can be expanded to the complete algorithmic description:
In the above the variable nogt10 is the number greater than 10% above the
average value. It is easy to argue that after exiting the while loop, count
is set to the number of positive numbers entered. Before entering the loop
count is set to zero and the first number is entered, that is count is one less
than the number of numbers entered. Each time round the loop another
number is entered and count is incremented hence count remains one less
than the number of numbers entered. But the number of numbers entered
is one greater than the number of positive numbers so count is therefore
equal to the number of positive numbers.
A main() program written from the above algorithmic description is
given below:
void main()
{
const int NE = 200; // maximum no of elements in array
float sum = 0.0; // accumulates sum
int count = 0; // number of elements entered
int nogt10 = 0; // counts no greater than 10%
// above average
float x; // holds each no as input
float indata[NE]; // array to hold input
float average; // average value of input values
int i; // control variable
181
cout << "Enter numbers, -ve no to terminate: " << endl;
cin >> x;
while (x >= 0.0)
{
sum = sum + x;
indata[count] = x;
count = count + 1;
cin >> x;
}
// calculate average
average = sum/count;
// Output results
cout << "Number of values input is " << n;
cout << endl
<< "Number more than 10% above average is "
<< nogt10 << endl;
}
outliers.cpp
Since it was assumed in the specification that there would be less than
200 values the array size is set at 200. In running the program less than 200
elements may be entered, if n elements where n < 200 elements are entered
then they will occupy the first n places in the array indata. It is common
to set an array size to a value that is the maximum we think will occur in
practice, though often not all this space will be used.
182
An array has been used to hold the six counts. This allows the program
to increment the correct count using one statement inside the loop rather
than using a switch statement with six cases to choose between variables if
separate variables had been used for each count. Also it is easy to change the
number of sides on the dice by changing a constant. Because C++ arrays
start at subscript 0 the count for an i occurring on a throw is held in the
i-1th element of this count array. By changing the value of the constant
die_sides the program could be used to simulate a die_sides-sided die
without any further change.
#include <iostream.h>
#include <stdlib.h> // time.h and stdlib.h required for
#include <time.h> // random number generation
void main()
{
const int die_sides = 6; // maxr-sided die
int count[die_sides]; // holds count of each
// possible value
int no_trials, // number of trials
roll, // random integer
i; // control variable
float sample; // random fraction 0 .. 1
183
cout << endl << "Number of occurrences of "
<< (i+1) << " was " << count[i];
}
cout << endl;
}
throwdie.cpp
This is the same as a normal array declaration but the size of the array
is not specified. This is illustrated in the following example which returns
the average value of the first n elements in a real array.
return sum/n;
} // end meanarray
meanarry.cpp
184
If when this function was called the value given for the parameter n
was greater than the number of elements in the actual array replacing the
parameter A then an incorrect result would be returned.
The function meanarray could be used as follows:
const int NE = 100;
float average, data[NE];
int i, m;
{
int i; // local control variable
for (i = 0; i < size; i++)
C[i] = A[i] + B[i];
} // End of addarray
The function addarray could be used as follows:
float one[50], two[50], three[50];
.
.
addarray(20, one, two, three);
185
Note that the parameter size could have been replaced with any value
up to the size that was declared for the arrays that were used as actual
parameters. In the example above the value of 20 was used which means
that only the first 20 elements of the array three are set.
Also note that the input parameters A and B have been declared in the
function head as being of type const float. Since they are input param-
eters they should not be changed by the function and declaring them as
constant arrays prevents the function from changing them.
char s1[10];
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
In the first case the array would be allocated space for eight characters,
that is space for the seven characters of the string and the null character. In
the second case the string is set by the declaration to be twenty characters
long but only sixteen of these characters are set, i.e. the fifteen characters
of the string and the null character. Note that the length of a string does
not include the terminating null character.
186
23.5.1 String Output
A string is output by sending it to an output stream, for example:
would print
would set the string s1 as follows when the string "first" is entered (with-
out the double quotes)
|f|i|r|s|t|\0|e|\0|
Note that the last two elements are a relic of the initialisation at declaration
time. If the string that is entered is longer than the space available for it
in the character array then C++ will just write over whatever space comes
next in memory. This can cause some very strange errors when some of your
other variables reside in that space!
To read a string with several words in it using cin we have to call cin
once for each word. For example to read in a name in the form of a Christian
name followed by a surname we might use code as follows:
187
cin >> surname;
cout << "The name entered was "
<< christian << " "
<< surname;
The name would just be typed by the user as, for example,
Ian Aitchison
// IEA 1996
// Example program which copies a specified
// input file to a specified output file.
// It is assumed that the input file holds a
// sequence of integer values.
#include <iostream.h>
#include <fstream.h>
int main()
{
ifstream ins; // declare input and output
ofstream outs; // file streams
char infile[20], outfile[20]; // strings for file names
int i;
188
<< " for input" << endl;
return 1; // exit with code 1 for failure
}
outs.open(outfile);
if (outs.fail())
{
cout << "Could not open file " << outfile
<< " for output" << endl;
return 1; // exit with code 1 for failure
}
// close files
ins.close();
outs.close();
return 0; //return success indication.
}
This program assumes that the file names entered by the user do not contain
more than 19 characters. Note how a space character was output after each
integer to separate the individual values in the output file.
23.6 Summary
• An array is used to store a collection of data items which are all of the
same type.
189
dices for elements of arrays are in range when verifying the correctness
of your programs.
• Strings can be input and output via the input and output streams,
cin and cout.
How many elements has the array day? If the declaration is changed
to
190
int A[10], i;
for (i=1; i<=10; i++)
cin >> A[i];
7. Write a function heading for a function which will double the first n
elements of an array. If the function was amended so that it would
return false if n was larger than the size of the array how should the
function heading be written? If the function was to be changed so that
a new array was produced each of whose elements were double those
of the input array how would the heading be written?
23.8 Exercises
1. To familiarise yourself with using arrays write a program that declares
two float arrays, say with 5 elements each, and carries out the fol-
lowing:
(a) Input some data from the user into the two arrays.
(b) Output the sum of the elements in each of the two ar-
rays.
(c) Output the inner product of the two arrays - that is the
sum of the products of corresponding elements A[0]*B[0]
+ A[1]*B[1]+ ....etc.
(d) Produce an estimate of how different the values in the
two arrays are by evaluating the sum of squares of the
differences between corresponding elements of the two
arrays divided by the number of elements.
Start by only entering and printing the values in the arrays to ensure
you are capturing the data correctly. Then add each of the facilities
above in turn.
191
increment. Having calculated the interval counts draw the Histogram
by printing each bar of the Histogram as an appropriately sized line
of X’s across the screen as below
0 - 9 16 XXXXXXXXXXXXXXXX
10 - 19 13 XXXXXXXXXXXXX
20 - 29 17 XXXXXXXXXXXXXXXXX
etc.
192