Title: Topics this week
1Topics this week
- Computer Programming absolute basics
- Program Life-Cycle Phases
- Creating an Algorithm
- Machine Language vs. High Level Languages
- Compilation and Execution Processes
- Problem-Solving Techniques
2What is Computer Programming?
- It is the process of planning and implementing a
sequence of steps (called instructions or
commands) for a computer to follow in order to
solve a problem.
. . .
399.99 of Programs
Nearly all of programs you write will involve
commands to
- Reserve space to store information
- Getting some information from a user and storing
it in the space you reserved - Doing something with the information
- Displaying results on the screen
4Program SkeletonIll explain the details later
include ltiostreamgt using namespace std int
main() return 0
This bit of code is your starting point for
nearly all programs you will be writing RUN IT
CHRIS
5Programs do something with information
This program uses the send to command working
with the cout (display destination) command to
send some text (a string) information to the
screen. RUN IT CHRIS
include ltiostreamgt using namespace std int
main() cout ltlt one plus one ltlt
endl return 0
endl is the carriage return command. and the last
letter is a letter l (el) not a number 1 (one).
6Programs do something with information
The ltlt command sends a piece of information
somewhere. cout is the destination here for that
information
include ltiostreamgt using namespace std int
main() cout ltlt one plus one ltlt
endl return 0
The text information is enclosed by
double quotes. DONT FORGET to put both sets of
double quotes in
7Programs do something with information
include ltiostreamgt using namespace std int
main() cout ltlt one plus one ltlt 1 1 ltlt
endl return 0
We can do more with the ltlt send command
Here I have put in a simple sum. Using 2
numbers. Note not in quotes. The computer works
out the result of the sum (2) and send the result
to the screen
8Programs do something with information
include ltiostreamgt using namespace std int
main() cout ltlt Result ltlt (34.45 3.2)/
(19.4 1) ltlt endl return 0
We can do complicated sums if we want
9Programs do something with information
Now this program can only do one sum. Also what
do these numbers mean? We can make the program
more friendly and flexible By using the reserve
space command.
include ltiostreamgt using namespace std int
main() cout ltlt Result ltlt (34.45 3.2)/
(19.4 1) ltlt endl return 0
10Programs do something with information
Reserving Storage Space Command Putting
information into reserved space command
include ltiostreamgt using namespace std int
main() double wages1 double wages2 wages1
10.50 wages2 35.63 cout ltlt Total wages
ltlt wages1 wages2 ltlt endl return 0
Order the computer to create 2 storage locations
and use the names wages1 and wages2 to remember
the locations
Order the computer to put the values in storage
location called wages1 and storage location
called wages2
11Names for storage locations
- There are rules in programming languages that
restrict what you can call the storage locations
you reserve. - In C they are
- No spaces allowed.
- double wage 1
- double Room height
The space between wage and 1 and between Room and
height is illegal. The computer will
COMPLAIN. SOLUTION remove the space. or
substitute with an underscore character _
12Names for storage locations
- Must not start with a number.
- double 1wage
- double 2Roomheight
- Must only use letters and numbers.
- double wage1 is illegal.
Note you CAN use numbers in names of storage
locations but it must not START the name.
13Names of Storage locations
- Must be made up from the letters a to z, upper
and lower case, the underscore character _ and
numbers 0 to 9. - Must NOT start with a number.
14Programs do something with information
Getting information from the user command
Again the program could be more flexible. Problem
is that we have to manually change the values of
wages1 and wages2 then recreate the program for
different numbers
include ltiostreamgt using namespace std int
main() double wages1 double wages2 cin gtgt
wages1 cin gtgt wages2 cout ltlt Total wages
ltlt wages1 wages2 ltlt endl return 0
cin and gtgt commands work together to get
information from the keyboard. Note the gtgt get
from command arrow directions are opposite to
the send to ltlt arrows
15Programming Life Cycle
- Problem-Solving Phase (focus today)
- Analysis and Specification
- General Solution ( Algorithm )
- Test/Verify (Desk check)
- Implementation Phase
- Concrete Solution ( Program )
- Test/Verify (run with test data)
- Maintenance Phase
- Use
- Maintain
16Problem-Solving Phase
- ANALYZE the problem and SPECIFY what is REQUIRED
i.e. what the solution must do. Work out what
bits of information are given, or that can be
assumed. Work out which bits of information are
unknown and need to be worked out. - Develop and write down on a piece of paper
GENERAL SOLUTION (ALGORITHM) to solve the
problem. That is specify how the information that
is given and assumed can be manipulated to work
out our unknowns. - VERIFY that your solution really solves the
problem. How will you know whether your solution
is correct? What tests do you need to do to
demonstrate the program is working.
17Example
- A programmer needs an algorithm (step by step
process) to determine an employees weekly wages.
-
- First thinkHow would I do the calculations be
done by hand? - Is there any information that is given or I can
assume? - What is the unknown information?
- Can I work out the unknown information from the
known?
18Analysis Look at a typical Employees Wages
- Information I can assume
- 40 hours normal week
- Normal Hourly Rate of pay 5.00/hour
- Overtime rate of pay 8.00/hour
- Information that will be given
- Actual hours worked in one week
- Information that needs working out
- How much the employee earns
19Can I find the unknown from the known?If I can
write down the steps.We call these steps the
ALGORITHM
20Analysis
A first attempt at an Algorithm to Determine an
Employees Weekly Wages
- Store the employees NormalRate, OvertimeRate and
NormalHours - NormalHours 40.0
- NormalRate 5.00
- OvertimeRate 8.0
- Get HoursWorked from the user
- Calculate the wages
- IF HoursWorked gt NormalHours then .
- Display the answer
simple
simple
complex needs more analysis
simple
It is written in English! We call this pseudocode
21Further Analysis
Refining Step 3 Calculate Wages
- IF the employee worked overtime then his wages
equals how much he earned doing overtime plus how
much he earned at normal rate, otherwise his
wages equals how much he earned at normal rate.
What is the condition? How do we know whether he
did any overtime?
The actual hours worked (HoursWorked) is greater
than Hours in normal week (NormalHours)
22Refining Algorithm Calculate Wages
Refined Algorithm in English
If he did overtime (i.e. the actual hours worked
(HoursWorked) is greater than Hours in normal
week (NormalHours)) then wages will equal
NormalHours times NormaRate plus overtime hours
times overtime rate, where overtime hours equals
HoursWorked minus NormalHours otherwise wages
equals Hoursworked times NormalRate
Algorithm in Pseudocode English
- IF HoursWorked gt NormalHours then
- OvertimeHours HoursWorked - NormalHours
- wages NormalHours NormalRate OvertimeHours
OvertimeRate - ELSE
- wages HoursWorked NormalRate
simple
simple
23Use 2 examples of 30 hours and 50 hours Why?
Desk Check Algorithm
Once you have reached a point where the algorithm
cannot be refined any more. You must verify the
algorithm
What are the employees wages in each case?
- Case 1 30 hours worked
- x 5.00 150.00
___________
150.00
Case 2 50 hours worked 40 x 5.00
200.00 10 x 8.00 80.00
___________
280.00
24Implementation
- We cannot simply write this pseudocode algorithm
as a program. - It is merely a program DESIGN
- YOU have to convert the DESIGN to your chosen
programming language (e.g. C) - A good design is one that can be easily converted
into code. - A poor design is difficult to convert
- A design should be language independent
25So what is a Programming Language?
- It is a language with strict grammar rules,
symbols, and special words used to construct a
computer program.
26Why a programming language? What wrong with
English?
- Computers dont understand English!
- English is a natural language and requires each
of us to understand meaning by context. - For Example
- Lung Cancer in Women Mushrooms
- Red Tape Holds Up New Bridges
- Hospitals are Sued by 7 Foot Doctors
- Star's Broken Leg Hits Box Office
- Villagers Grill Gas Men
27Computers are really stupid!
- Computers do not understand anything!
- well not quite they understand what a 1 and a 0
is. - Computers follow instructions
- Instructions have to be written in 1s and 0s
- Such instructions are called machine code.
28Machine language
- Machine languages
- 11000000 000000000001 000000000010
- Add contents of memory location 1 to contents of
memory location 2 - Horrid to write programs!
- Assembly
- ADD 1 2
- Needs an assembler to translate to machine
language
29Levels of Programming Languages
- Levels of Computer Languages
- Low (long way from English)
- machine language, assembly
- not portable
- High (Closer to English)
- COBOL, Pascal, FORTRAN, Logo, Basic, Prolog C, C
30High level languages
- Deliberately terse. Must be unambiguous.
- Must be flexible enough to easily implement
algorithms. - Fairly portable
31Creating machine (executable) code from C
source code Compilation and linking
source code
Preprocessor
Compiler checks whether the modified source
code obeys the laws of the C language
Modified Source code
Preprocessor searches for lines beginning with
symbol and modifies the source code
according to the instruction. E.g. include
instruction inserts a file referred to
by ltfilenamegt or filename
Compiler
object code
Linker adds machine code from library routines
used. These routines are usually specified by
include
Linker
Executable code
32Possible Break now Chris!
33Controlling the order that commands/instructions
are executed
The Basic Control Structures of programming
- Basic idea is that commands are carried out in
the order they appear one after another. That is
we define the sequence of commands. - selection/branching is used to execute different
commands depending on certain conditions recall
the payroll example earlier when we calculated
wages two ways dependent on the number of hours
worked. - Looping/repetition is used to repeat commands
again and again. For example if we had many
employees we might want to repeat the part of the
algorithm that inputted the hours worked and
calculation and display of wages again and again
for every employee.
34SEQUENCES
. . .
Statement
Statement
Statement
Note logical order!
- Reserve space to store values
- Get the user to input hours worked and store the
value - Calculate the wages
- Display wages
35SELECTION (branch)
IF Condition THEN Statement1 ELSE Statement2
True
Statement1
Statement
Condition
. . .
Statement2
False
IF HoursWorked gt NormalHours then
OvertimeHours HoursWorked NormalHours
wages NormalHours NormalRate OvertimeHours
OvertimeRate ELSE wages HoursWorked
NormalRate
36LOOP (repetition)
WHILE Condition DO Statement1
False
. . .
Condition
True
37Loop (repetition) Example
Repeat While there are more Employees to
process Get the user to input HoursWorked IF
HoursWorked is greater than NormalHours
then Wages .. ELSE (otherwise) Wages
Display the Wages End repeat
38Problem Solving Techniques
- OVERCOME MENTAL BLOCK -- by rewriting the problem
in your own words - DRAW A FIGURE/DIAGRAM
- ASK QUESTIONS
- What information must be displayed? What is
information do you know? what do you NOT know and
need? what information can you assume to make
things simpler for yourself?, What kind of
information am I manipulating (whole numbers,
numbers with decimal points, text? What would be
good identifiers (names) for the information. - Where does the information come from? Is it
given? Can it be assumed? Do you get it from the
user? do you calculate it? do you get it from a
file? - Can you identify what is input and what is to be
output? - What are the processes?
- Do you need to repeat steps
- What are the conditions?
- Do you need to do different things in different
situations? - What are the conditions
39Problem Solving Techniques
- LOOK FOR FAMILIAR THINGS -- certain situations
arise again and again. E.g. Am I repeatedly
getting input from the user? creating tables,
adding up lists of numbers, reading from files,
Searching for maximum or minimum values. - Do you know any equations?
- Find the wall area of a room, find the stopping
distance of a car.
40Problem Solving Techniques
- Stepwise refinement -- break up large problems
into manageable units. - SIMPLIFY
- Can you solve a simpler but related problem?
- For example a program to calculate wall areas of
rooms for a decorating company. - Solve problem assuming simple rectangular rooms
without doors and windows. - Solve by analogy -- it may give you a place to
start. In a broader sense than looking for
familiar things. - E.g. Finding the student with the highest and
lowest score is analogous to finding the highest
and lowest temperature.
41Problem Solving
- USE MEANS-ENDS ANALYSIS
- Where you often know start conditions and know
what the end goal is. - Identify intermediate goals then think how you
get from start to the intermediary goals choosing
the most appropriate means for the problem. - E.g. I am hungry and I want to be full
- What's the difference between what I have and
what I want? An empty stomach. What changes the
emptiness of my stomach? Eating food. But I
don't have any food. I want to have some food.
What's the difference between what I have and
what I want? The presence of food. What changes
the presence of food? Searching, shopping,
hunting, growing food. I search for food, but
there is nothing available. I decide to shop for
food. What do I need to shop? Money. But I
don't have any money. I want some money. How do
I get money? Withdraw from the bank, sell
something, steal. I decide to withdraw from the
bank. I want some money from the bank. What do
I need to get money from the bank? I must be at
the bank. I want to be at the bank. What is the
difference between where I am now and where the
bank is? Distance. What changes distance?
Walk, cycle, drive, bus. ..... and so on
42Problem Solving Techniques
- BUILDING-BLOCK APPPROACH -- can you solve small
pieces of the problem? And then join them up - E.g. a large application like a word processor
has many functions. (Text manipulation, Tables,
drawing) - Do not try to solve all at once.
43Result of Problem solving
- One or more pages of rough work that sketches
your ideas of problem requirements, of user
inputs, of outputs, of constants, of conditions
for repetition and selection, of assumptions. - A formal written design that include.
- inputs, Processes, Outputs, assumptions.
- Write steps to process input unambiguously using
a semi formal notation (PDL, Flowchart or
structure diagram?) Can you translate each step
of the plan into C easily? - Verification/testing procedures documented (A
test table).
44What we are aiming for is Structured Methodical,
Systematic Approach to Programming
- Advantages
- Not one giant step, but breaks in to smaller and
smaller chunks. - Programmer concentrates on details
- Easy to do in teams
- Easy to keep track of development
- Creates more reliable and robust programs.
- Errors isolated
- Design written in code
- Improves reliability
- Minimizes risk of Failure
- Faster development
- Makes more possible reuse and extensibility.
45Summary
- So take any problem, apply problem solving
approaches. To find a solution, write it down in
English. - Write it down more formally in Pseudo-code (PDL),
or as a structure diagram or a flow chart. - Start your programming environment and convert
your pseudo-code to C - Order the computer to convert the C to machine
language (compile) - Order the computer to load the machine language
into memory and execute (Run).
46Checkpoint
- What are the absolute basics of programming in
C - What are the phases of software development
process? - Do you know what an algorithm is?
- What is difference between pseudocode and source
code? - What is a low level language and what is a high
level language? - How do you get from machine code to executable
code. i.e what does the preprocessor, compiler
and linker do? - What are the main ways instructions are
controlled? - What are the main techniques to help problem
solving? - What do I mean by structured programming? and
what are the advantages of structured programming.
47Next Week
- Short Test in tutorials on absolute basics of
C. - Check blackboard for example paper.
48Bye Bye