1. Introduction to OO Programming
in C++ and Java
The lecturer of this course
Dr Vasos Pavlika
Vasos.Pavlika@conted.ox.ac.uk
vp4@soas.ac.uk
vpavlika@lse.ac.uk
VPavlika@sgul.ac.uk
(Vas for short)
2. Course Lecturer
Dr Vasos Pavlika, Subject Lecturer at SOAS, University of
London.
Subject Lecturer and online Tutor in Mathematical
Economics at SOAS, University of London.
Senior Teaching Fellow, SOAS, University of London
Lecturer for the Department for Continuing Education,
University of Oxford.
Associate Lecturer: New College, Oxford
Saturday School Lecturer: The London School of Economics
and Political Science.
Associate Tutor: St George’s Medical School, University of
London.
Consultant Mathematician.
Previously Senior Lecturer at the University of Westminster.
Field Chair at the University of Gloucestershire
3. Course Book
You should get a copy
Programming and Problem Solving with C++
by Nell Dale 4th
Edition
ISBN 07637 0798-8
I will simply refer to this as Dale. E.g. Please
do exercises 2-4 on page 101 in Dale.
There is also a version available that includes
a student edition of the Visual C++ Program
Development Studio.
4. NOTE: Additional Books
I may refer to the text: C++ from the Ground
Up, 2nd
Edition, by Herbert Schildt, ISBN:
0078824052
There are many good C++ books around, the
net is also a good source of information.
I will occasionally be handing out notes.
I can send you the notes (Powerpoint slides)
provided you email me first so that I have
your reply addresses.
5. Lecture Format
As of next week, each lecture will comprise a “Warm up Exercise” which
consists of the writing of little programs in C++ using your
understanding of the previous week’s material, occasionally you
may have to give descriptive solutions.
I will be using Microsoft Powerpoint presentations to introduce the
material.
There will be Tutorial Questions set weekly or fortnightly which can be
used to obtain completion of the course and the associated CATS
points.
A series of portfolio exercises and tutorial exercises will be set
during the course, these exercises will constitute a log book of
exercises that will count as the coursework component for this
course.
These exercises will consists of programs as well as descriptions of
topics covered in the lectures.
6. Portfolio Exercises
There will be two portfolio exercises
for each 10 week course one in C++
the other in Java.
These are assessed and counts
towards the award of the CATs Points
You can not be awarded the CATs
points if your attendance falls below
70%.
7. Getting onto the system here at Oxford
Click TeachingTerminal1
contedehc
murphyslaw
Locate quincy
Tools->option->Build goto compiler
and type c:MinGW
ok
8. What is computer programming?
Getting a computer to do what would
be extremely time consuming and
inaccurate if a person was to do it.
OR
Processing input data to produce an
output.
9. Why use Computers?
Computers we know are very good at
doing repetitive tasks without making
mistakes and without complaining.
It would be difficult to get a human to
sum the first 10,000 integers and of
course to get it right, this would be
child’s play for the computer.
10. The IDE
The IDE (Integrated Development
Environment) used here at OUDCE is
Quincy
Go to programs
Locate Quincy
Right click on the mouse when on
Quincy to copy it onto the desktop
Launch Quincy
11. The Problem is that computer
programming
It is very different from what many of you
have done before.
It is the least “doable” subject from books.
One can not just read about programming and
expect to become a master in it.
Requires creative problem solving (thinking)
Requires courage and confidence
Requires good organisation
Requires practice
Requires a version of C++ at home
12. The good thing is
We are all natural problem solvers!
In our lives we are constantly solving
problems.
What to have for lunch?
Where to go on holiday?
How much will I earn this week at work?
13. The bad thing is
Many have difficulties generalising
their day to day problem solving skills
to the precision required for problem
solving in computing.
E.g. A very simple example
Bobs Bank
14. Bobs Bank
Problem
Given the current rate of interest, how
much will all my customers have in their
deposit accounts at the end of…
1,2,3,…N years?
We want to write a program to solve
this problem.
15. Computers are a bit dim!
We have to detail precisely the
instructions… There is no Mr Data
from Star Trek here, no computer
understands English!
We must be able to figure out how to
solve the problem first (on paper)
before we attempt to write a
computer program to tackle the task.
17. The Waterfall model
Many people use “code and fix”,
which means you sit at your
computer, code and correct bugs
when or if they are encountered.
This is fine if your program is small.
For programs with thousands of lines
of code, you will have to do things
away from the computer
18. Waterfall Model continued
The standard Waterfall Model for systems development
is an approach that goes through the following steps:
Document System Concept (what am I going to do)
Identify System Requirements and Analyze them
Analysis: what is it that I am going to build?
Break the System into Pieces (Architectural Design)
Design Each Piece (Detailed Design)
How am I going to achieve this?
Code the System Components and Test them
Individually (Coding, Debugging, and Unit Testing)
Sometimes this is called the implementation phase
19. Waterfall Method continued
Integrate the Pieces and Test the System
(System Testing)
Deploy the System and Operate It
Maintain the system updating the system
when the need arises
Bring out later/better editions
This model is widely used on large
governmental systems, particularly by the
Department of Defense (DOD).
20. The Waterfall Model
One of the draw backs of the Waterfall
Model is that each stage in the cycle (or
process) must be completed before
moving on to the next stage.
This can cause timing problems i.e. one
simply does not have enough time to
complete each task.
Are there other (and hopefully better)
ways of doing things?
22. Rapid Application Development
(RAD)
DEFINITION
a software development process that allows
usable systems to be built in as little as 60-
90 days, often with some compromises.
Drawback: the final product often does not
meet the exact requirements originally
requested, there is a trade off in
requirements.
23. RAD continued
PRINCIPLES BEHIND THE DEFINITION
In certain situations, a usable 80% solution can be
produced in 20% of the time that would have been
required to produce a total solution.
In certain situations, the business requirements for a
system can be fully satisfied even if some of its
operational requirements are not satisfied.
In certain situations, the acceptability of a system can
be assessed against the agreed minimum useful set of
requirements rather than all requirements.
24. With conventional methods, there is a long delay
before the customer gets to see any results.
With conventional methods, development can take so
long that the customer's business has fundamentally
changed by the time the system is ready for use.
With conventional methods, there is nothing until
100% of the process is finished, then 100% of the
software is delivered.
Hopefully this is still what is required by the user
PROBLEMS ADDRESSED BY RAD
25. Why Use RAD?
Problems with USING RAD
to prevent cost overruns
(RAD needs a team already disciplined in cost management)
to prevent runaway schedules
(RAD needs a team already disciplined in time management)
Good points for USING RAD
to converge early toward a design acceptable to the
customer and feasible for the developers
to limit a project's exposure to the forces of change
to save development time, possibly at the expense of
economy or product quality
27. Bobs Bank (tidy version)
Get the current interest rate (say 6%)
Get the number of years ahead we want the
results for (1,2,3,N)
Get their current deposit value
Work out the calculation
If years equals 1 then
use equation 1 and Display the results
If years equals 2 then
use equation 2 and Display the results
If years equals 3 then
use equation 3 and Display the results
If years equals anything else
display an error message
28. //Bobs Bank
#include <iostream>
using namespace std;
int main() {
double interest;
double deposit;
double value;
int years;
cout << "hello, please enter the current interest rate : ";
cin >> interest;
cout << "now, please enter the initial deposit : ";
cin >> deposit;
cout << "now enter the number of years 1,2 or 3 ahead to calculate : ";
cin >> years;
if (years == 1) {
value = deposit*(1 + interest);
cout << "Value after " << years << " year is " << value << endl;
}
else
if (years == 2) {
value = deposit*(1 + interest)*(1 + interest);
cout << "Value after " << years << " years is " << value << endl;
}
else
if (years == 3) {
value = deposit*(1 + interest)*(1 + interest)*(1 + interest);
cout << "Value after " << years << " years is " << value << endl;
}
else
{
cout << "Invalid number of years entered" << endl;
}
//this is Bank1.cpp
return 0;
}
30. Practice, Practice, Practice
Computer programming is more like
Learning a musical instrument
Learning to play a new sport
Driving a car
It is an active process
It is an incremental process
It constantly builds from previous knowledge
TRY NOT to get left behind as it is VERY
hard to catch up!
31. Why, What, How, Where and When
Why are you learning to program?
What will you learn?
How will you learn?
How will you be assessed?
Where will you learn?
When will you learn?
32. Why are you learning to Program?
Or what’s in it for me?
For purely academic interest (I wish!)
To get a job and pay off your loans!
Because you want to move onto
more courses here at Oxford or
elsewhere.
33. Why are you learning to Program?
Or What is in it for me?
Because it impacts on every subject
you take, the programming principles
you learn are applicable to other
programming languages.
Learning C++ and Java here at OUDCE
will enable you to pick up other
languages very easily.
34. Why C++
Supports procedural programming and object
oriented programming.
What is OO programming?
An object is a variable of type class
What is procedural programming?
Functions/procedures
C/C++ de-facto industry standard programming
language.
It works on the network here (I hope! We had
problems last year!)
35. Why C++
Friendly development environment and
good debugging tools.
Cheap for student edition
C++ rather than C because I/O friendlier,
easier introduction of functions and strings.
Supports Object Oriented Programming, C
does not.
Java is even nicer, does away with pointers
(hides their usage somewhat)
36. Procedural paradigm
Sequential
Program runs from top down, one command
performed, then move onto the next
Selection
Can make choices in a program
Iteration
Can repeat certain parts of your program which
are only terminated when certain criteria are
satisfied
38. What will you learn?
You will learn how to begin the
process of problem solving and
designing a solution.
You will learn how to write the
solution to a problem in an
unambiguous way.
You will learn how to verify the
solution i.e. Whether it is correct.
39. What will you learn?
You will learn how to use the C++
development environment to build
and debug your programs.
You will learn how to translate the
solution into C++ code in a
systematic way.
You will learn how to verify whether
the C++ code for the solution is
correct.
You will learn the basic syntax and
structure of simple C++ programs.
40. What you will learn?
You will learn how to apply the basic control
structures in C++; sequences, selection,
repetition, and subprogram (function)
invocation.
You will learn how to construct and use the
built in data structures; integer (int), double,
char, strings (strictly speaking this is not
built in!), arrays, files, structs and classes
You will learn the fundamentals of object
oriented programming by creating classes
and using objects
41. Overall Syllabus Goal (Term1)
To be able to:
investigate and analyse a “real world
problem”
Produce and verify a solution formally
Using sequences, selection, repetition and
subprogram invocation.
Using C++ implement and test your
solution - like we did with Bobs Bank
Introduce OO concepts
42. How will you learn?
Lectures with demonstrations, tutorials
and portfolio exercises.
You have a course book with exercises
and tutorials. (Sorry about the American
bias!)
Check the internet there is a huge
amount of material available
Check the library for resources
Try to find your own books to
complement the course book
43. How will you learn?
YOU will have to take responsibility for
learning to program by doing it. IT CAN
NOT BE CRAMMED!
You cannot learn to program by reading a
book – it is more like learning to play a
musical instrument or driving a car!
This is a 10 week course worth 10 CATs
points.
We estimate that you should try to put in at
least 2 hours at home per week during the
week away from the lab here
44. How will you learn?
Tutors (just me this year), are here to get
you out of holes, and give one to one advice
on techniques. Suggest approaches to
problems NOT to solve problems for you.
I am here to answer any questions on
written pre-lab and lab-exercises.
If you do not complete the set work in the
tutorial it is hoped that you will complete
the work in your own time as I follow on
from the previous weeks lecture each week!
45. How will you be assessed?
Working at home/in other times. You
should do this if you want any success.
Do not simply rely on exercises that I
set, please work from your book.
If you want you can email me your
work each week to look at and to give
you feedback.
46. How will you be assessed?
At the end of each term you will be
awarded the 10 CATs points (if you
have enrolled of course and created
appropriate programs and written
answers), you receive confirmation of
the award from the University of
Oxford
NOT FROM ME.
47. Resources and To Do List!
You need to purchase a course book, and
attempt exercises for next week.
Brush up on your basic windows skills,
learn to;
rename files
create folders and subfolders
copy & move files to and from hard disk
and floppy disk
delete files and folders
48. Resources and To Do List!
I will email the Powerpoint presentation to each
of you after each lecture for you to have,
tutorial questions will be given in the lectures.
I will also send source code for demonstration
programs.
You may want to download a free IDE and
compiler these are available on the internet.
E.g.http://www.bloodshed.net/dev/devcpp.html
There is even talk of a site for our course, I will
look into this for next week.
49. Resources and To Do List!
Summary
Get C++ on your computer at home.
Send me an email.
Buy Course book and do initial pre-
tutorial work.
Buy USB disks to take your work
home etc.
51. C++ Week 1.
Elements of a C++ Program.
In this text one will be introduced to C++
programming.
The material arose from the teaching
material used to deliver an Introductory
Programming module in C++ here at Oxford
over the past 10 years.
The first question one may wish to address
is what is the shortest C++ program one can
write? We will answer this question in due
course.
52. The anatomy of a C++
program
Every C++ program has one main section (actually
a function), where program execution starts and
terminates.
From within main we may declare variables
(quantities whose value change during run time),
one may make calls to small blocks of code usually
called functions which may carry out certain tasks
e.g. find the average of a set of numbers passed
to the function (this means values that the
function acts on, more to be said about this later).
Returning to the question what is the smallest
program one can write the solution is:
54. Shortest C++ program
There is no need to use #include, (you may
ask what is #include, this is a compiler
directive to include some library files that
comes with the system
i.e. a command to the compiler to include
some pre written code such as the file
iostream) as there is no input or output so
we do not need the iostream library (on
some earlier versions such as Turbo C++
one has to use iostream.h).
55. Explanation continued
There is no need to specify a return value
for main().
However, although C and C++ implicitly
assume an integer return value for main()
you should normally return an int (short for
integer) explicitly.
Usually return 0;
You do not need to declare an input
parameter type for main() but it is better to
use (void).
int main(void)
56. Explanation continued
You do not need put any code inside
main() but normally you should
specify return 0; to indicate to the
operating system that everything is
working satisfactorily.
Some compilers will give an error
message if this is not included not all.
57. #includes
These are libraries.
When you send the file to the compiler, the
preprocessor substitutes the #include with the
contents of the specified library file.
In this way you can create and use modules that
define functions that you only add to your code when
you need them.
If you included all the libraries in your programs, they
would take a considerable amount of time to process.
There are lots of different libraries available for many
different purposes.
58. #include
Note that input/output is defined in a
library, so if you want your program
to be able to do anything useful you
need to use #include <iostream>.
In the Turbo C++ IDE environment we
have to declare these libraries using
the .h extension. So one would write
#include <iostream.h>.
59. Namespaces
A namespace allows you to use your own
names without worrying about conflicts with
names that other programmers may have
used for their own variables etc.
However you need to make it explicit that you
are using a standard namespace by using
namespace std; i.e. using the .std (standard
extension). This is only appropriate for ANSI
C++ (American National Standards Institute).
See namespace1.cpp in directory
60. Namespaces
If you forget to add this line to your
code, the compiler will be unable to
recognise any of the keywords you
are using (again only appropriate in
ANSI C++).
61. Elements of a C++ program
cout <<
cout is the name of the standard output
stream, normally the console. The <<
operator reads the argument that follows
it and places it in the output stream that
precedes it.
>> is known as the extraction operator
<< is known as the insertion operator
Here are some valid cout statements:
62. cout<<
cout << "Hello"; //"Hello" is a string
//literal, the term after the // is a
comment and ignored by the
compiler during compilation.
cout << 27; // 27 is an integer value
cout << 2+3; // 2+3 is an expression
Calculations can be made after the
insertion operator
63. cout <<
cout << "result = " << 5+7;
One can concatenate operators on a
line.
Concatenate means to join
(amalgamate strings) more about this
later.
64. The new line character
To end a line of output you can use << "n"
or << endl;
The “n” is inherited from the C language
(inherit here is not in the sense of the OO
term, to be met much later on the course).
They are followed by the semicolon. These
statements are a LINE FEED directing the
cursor to the next line also known as the
new line character.
65. Variables
A variable is a segment of memory that has
been reserved for a data item that may change
value at run-time i.e. when we run the program.
Integer variables are numbers that do not have
a fractional part (non-decimal numbers).
They can be declared using the code below:
int x; so x is now an integer variable which can
change during program execution but can only
store integers.
66. More on variables
double variables are real variables (as in
real numbers).
They can store “larger” numbers than can
an int (integers).
These are declared using the double
keyword (reserved word).
Float variables are like doubles but
“smaller” declared using the keyword float.
Since memory is no longer in such short
supply they are falling into disuse
67. More on variables
If you do not initialise a numeric variable
when you declare it (i.e. give it a starting
value), be sure you initialise it before you
read it! You can declare and initialise several
variables at conception
For example:
int x = 1, y = 3;
Here two integer variables have been declared
and set equal to 1 and 3 respectively
= is the assignment operator not to be
confused with the equality operator of
mathematics or the == in comparisons
68. More on variables
in these last two statements two
variables x and y have been declared.
They have also been initialised with
the values 1 and 3 respectively
69. Strings
If you want to use strings remember to use
#include<string>
Strings are arrays of char (character) data.
(or #include<string.h>)
Note: When you declare strings, enclose
them in " ".
char data is enclosed in ‘’ , (single quotes).
Non initialised strings are empty, "".
70. Reserved Words
The C++ compiler uses words like int, double, float
etc, and they are therefore reserved, this means
that they have special meaning in C++.
They are not to be used to declare variables in a
program.
This means that one can not declare a variable
with the name double.
In short: Do not use them as variable names.
C++ like Java is case sensitive
71. Identifiers
Identifiers are used to name variables.
They must always begin with a letter; subsequent
characters may be a letter, number or underscore
_ but not a space or other character. An illegal
identifier would be 1Time because the variable
starts with a numeral and not a letter.
Note that C++ is case sensitive so that you can
use num1 and NUM1 in your code without
confusion.
One could also use Int as an identifier but this
would not be desirable.
72. cin
cin is the name of the standard input stream,
normally the keyboard. The >> operator reads
data from the input stream that precedes it and
places it in the argument that follows it. Take note
of the following characteristics.
the >> operator ignores leading white spaces
(<space>, <newline> and <tab> characters) and
takes as its input the first characters or numbers
in the input stream (from the keyboard or a file).
The behaviour depends on whether it is expecting
numeric or character data.
73. cin example
For example we could use:
int x;
cin >> x;
One would probably assist the user
by giving them a prompt informing
them that a value for x is required.
74. cin example
When reading integer data, >> may
take a + or - as a leading character
and continues to read in numeric
data until it encounters a non-integer
character (white space, non-numeric
or decimal point).
In the above example, typing +492A
will place 492 into the input stream.
76. cin example
When reading floating point data, >>
may take a + or - as a leading
character and stops at non-numeric,
but decimal points are accepted. In
the above example, typing .67a will
place 0.67 in the input stream.
string s;
cin >> s;
77. cin example
When reading string data, >> skips
leading white space and reads
everything into the input stream up
to but not including the next white
space.
Here is an example of how >> deals
with different data types in the input
stream.
79. input
Input i d s
12 5.9 London 12 5.9 London
-3 6.6 Paris -3 6.6 Paris
33.54 Hong Kong 33 0.54 Hong
80. Assignment statements.
Assignments take the form
Variable = Expression
// Note it is not read as equals in this context
// but as BECOMES as it is
in Turbo Pascal and
other languages.
Note: Do not confuse the assignment
operator = with the logical comparison or
test operator = = (this is a combination of
two equalities)
81. Assignment statements
You can combine the = operator with
other mathematical operators.
For example, x++; and ++x; are
shorthand for x = x + 1;
similarly x += 5; means x = x + 5;
this is known as incrementing.
83. modulo
If both arguments are integers, the
result is truncated to an integer,
otherwise the result is a floating
point number.
% modulo - the remainder of the
division of two integers.