Computer Programming Lecture 23. Summary of Previous Lecture In the previous lecture, we have learnt...

Post on 17-Dec-2015

221 views 1 download

Tags:

Transcript of Computer Programming Lecture 23. Summary of Previous Lecture In the previous lecture, we have learnt...

Computer Programming

Lecture 23

Summary of Previous Lecture In the previous lecture, we have learnt

Intellectual Property Types of Intellectual Property Rights

Copyrights Patents Trade Secrets

Laws Employees and Trade Secrets

Key intellectual Property Right Issues

Plagiarism Reverse engineering

Summary of Previous LectureOpen source codeCompetitive intelligenceCyber squatting

Today’s Lecture Programming in real life.

Introduction What is Problem Solving?

Problem Solving process. Algorithm

HistoryWorking DefinitionExamples

Today’s Lecture Algorithms to Programs Components of Algorithms

Variables and values InstructionsSequencesProceduresSelectionsRepetitionsDocumentation

Today’s Lecture Software Development Process Top Down Algorithm Design Summary

Where is programming in real life?

Short answer: all over the place!

Where is programming in real life?

Short answer: all over the place!

Introduction

People think in words: Like “The sky is so beautiful!”

The computer understand in ‘binary’.Which just means ones and zeros:

00111000100111. “Programming languages” are different

ways of taking your words and turning them into instructions that the computer can understand.

Introduction

Programs are a set of instructions for the computer.

There are three levels of programming languages.Machine level, i.e.; direct hardware commands

Middle level i.e.; Assembly languageHigher level i.e.; C, Java, C++, LISP etc.

Don’t worry.

Programming isn’t really that hard. The only thing you have to remember is that:

THE COMPUTER IS STUPID. Even if you really, really want it to do something, it

won’t do it unless you give it specific instructions! It only does what you tell it to do.

… the good news is that YOU are smart. … so you can make the computer do really,

really cool things.

Problem solving Programming is a process of problem

solving Problem solving techniques

Analyze the problem Outline the problem requirementsDesign steps (algorithm) to solve the problem

0100111010110010101010101001010101010100110010101010101001011010011101010101010010010111010011110101010111110101010001101…

sterilize(saw,alcohol);raise_hammer();lower hammer(fast);start(saw);/* etc. etc. */

Patient has elevated pressure in anterior parietal lobe

The Problem-solving Process

Problem

specification

Algorithm

Program

Executable (solution)

Design

Implementation

Compilation

"Doctor, my head hurts"

Analysis

1. Sterilize cranial saw2. Anaesthetize patient3. Remove top of skull4. Get the big spoon...5. etc., etc.

sterilize(saw,detol);raise_hammer();lower hammer(fast);start(saw);/* etc. etc. */

The Problem-solving Process

Problem specification

Algorithm

Program

Executable (solution)

Analysis

Design

Implementation

Compilation

"Doctor, my head hurts"

Patient has elevated pressure in anterior parietal lobe.

1. Sterilize cranial saw2. Anaesthetize patient3. Remove top of skull4. Get the big spoon...5. etc., etc.

010011101011001010101010100101010101010011001010101010100101101001110101010101001001011101001111010101011111010101000110100001101...

The Problem-solving Process

Problem specification

Algorithm

Program

Executable (solution)

Analysis

Design

Implementation

Compilation

A sequence of instructions specifying the steps required to accomplish some task.

The idea behind the computer program Solution achieved in finite amount of time

Solves a well-specified problem in a general way

Formally: “An algorithm is an ordered set of unambiguous executable steps, defining a terminating process.”

Algorithm

Algorithm –History Named after:

Muhammad ibn Musa al-Khwarizmiم�ي �خ�و�ار�ز� �ل ا م�وس�ى �ن ب م�ح�م"د �د�الله ع�ب

of Khowarezm (now Khiva in Uzbekistan) Circa 780-850 C.E. (Common Era)

was a Persian, mathematician, astronomer and geographer, a scholar in the House of Wisdom in Baghdad.

Book on arithmetic: Hindu numeration, decimal numbers, use of zero, method for

finding square root Latin translation (c.1120 CE): “Algoritmi de numero Indorum”

Book on algebra Hisab al-jabr w’al-muqabala الجبر حساب في المختصر الكتاب

والمقابلة

Formally: “An algorithm is an ordered set of unambiguous executable steps, defining a terminating process.”Ordered set of steps: structure!Executable steps: doable!Unambiguous steps: follow the directions!Terminating: must have an end!

Algorithm – Working Definition

Algorithm -- Examples

A cooking recipe Assembly instructions for a model The rules of how to play a game VCR instructions Description of a martial arts technique Directions for driving from A to B A knitting pattern A car repair manual

Algorithm – Examples .. Recipe for Almond and honey slice

Almond and Honey Slice

1/2 quantity Shortcrust Pastry

185 g unsalted butter

100 g castor sugar

5 tablespoons honey

50 ml cream

300 g flaked almonds

Preheat oven for 200° C

Line a 30 cm 20 cm baking tray with baking paper, and then with pastry

Bake blind for 20 minutes, then remove weights and foil

Turn oven up to 220° C.

Bring remaining ingredients to a boil, stirring.

Spread evenly over pastry.

Bake until topping is bubbling and has caramelised evenly, about 15 minutes.

Cool before cutting into fingers or squares.

From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.

Almond and Honey Slice

1/2 quantity Shortcrust Pastry

185 g unsalted butter100 g castor sugar5 tablespoons honey50 ml cream50 ml brandy or any

other liqueur or spirit300 g flaked almonds

Preheat oven for 200° C

Line a 30 cm 20 cm baking tray with baking paper, and then with pastry

Bake blind for 20 minutes, then remove weights and foil

Turn oven up to 220° C.

Bring remaining ingredients to a boil, stirring.

Spread evenly over pastry.

Bake until topping is bubbling and has caramelised evenly, about 15 minutes.

Cool before cutting into fingers or squares.

From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.

Instructions are given in the order in which they are performed (“executed”)

Correct Algorithm?Cut chicken into pieces and

brown the pieces on all sides in a casserole dish in hot olive oil.

Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and cook until onion is golden.

Add bay leaf, whole tomatoes, and chicken soup.

When the soup boils add salt, saffron and rice.

Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 20 minutes or until the rice is tender.

Add beans and artichokes during last 10 minutes of cooking.

From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.

Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.

Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden.

Add bay leaf, whole tomatoes, and chicken broth.

When the broth boils add salt, saffron and rice.

Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 20 minutes or until the rice is tender.

Add beans and artichokes during last 10 minutes of cooking.

From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.

Correct Algorithm?

Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.

Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden.

Add bay leaf, whole tomatoes, and chicken broth.

When the broth boils add salt, saffron and rice.

Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 10 minutes.

Add beans and artichokes.

Cover, and bake for another 10 minutes or until rice is tender.

Correct Algorithm?

From Algorithms to Programs

Problem

C ProgramC Program

AlgorithmAlgorithm: A sequence of instructions describing how to do a task (or process)

Components of an Algorithm Variables and values Instructions

SequencesProceduresSelectionsRepetitions

Also required: Documentation

Values

Represent quantities, amounts or measurements

May be numerical or alphabetical (or other things)

Often have a unit related to their purpose

Example:Recipe ingredients

Almond and Honey Slice

1/2 quantity Shortcrust Pastry

185 g unsalted butter

100 g castor sugar

5 tablespoons honey

50 ml cream

300 g flaked almonds

Preheat oven for 200° C

Line a 30 cm 20 cm baking tray with baking paper, and then with pastry

Bake blind for 20 minutes, then remove weights and foil

Turn oven up to 220° C.

Bring remaining ingredients to a boil, stirring.

Spread evenly over pastry.

Bake until topping is bubbling and has caramelised evenly, about 15 minutes.

Cool before cutting into fingers or squares.

From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.

Almond and Honey Slice

1/2 quantity Shotcrust Pastry

185 g unsalted butter

100 g castor sugar

5 tablespoons honey

50 ml cream

50 ml brandy or any other liqueur or spirit

300 g flaked almonds

Preheat oven for 200° C

Line a 30 cm 20 cm baking tray with baking paper, and then with pastry

Bake blind for 20 minutes, then remove weights and foil

Turn oven up to 220° C.

Bring remaining ingredients to a boil, stirring.

Spread evenly over pastry.

Bake until topping is bubbling and has caramelised evenly, about 15 minutes.

Cool before cutting into fingers or squares.

From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.

Variables

This jarcan contain

10 cookies

50 grams of sugar

3 slices of cake

etc.

ValuesVariable

• Are containers for values – places to store values

• Example:

Restrictions on Variables

Variables may be restricted to contain a specific type of value

Components of an Algorithm

Values and Variables Instruction (a.k.a. primitives) Sequence (of instructions) Procedure (involving instructions) Selection (between instructions) Repetition (of instructions) Documentation (beside instructions)

Instructions (Primitives) Some action that is

simpleunambiguous that the system knows about... ...and should be able to actually do

Instructions – Examples

Take off your shoes Count to 10 Cut along dotted line Knit 1 Purl 2 Pull rip-cord firmly Sift 10 grams of arsenic

Directions to perform specific actions on values and variables.

Instructions -- Application Some instructions can only be applied to a

specific type of values or variables Examples:

Instructions (Primitives) -- Recommendations

When writing an algorithm, make each instruction simple and unambiguous

Example:

Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.

Cut chicken into pieces.

Heat olive oil in a casserole dish.

Brown the chicken pieces in the casserole dish.

Procedure A named sequence of instructions So that you can

Refer to it collectively (by name) ...instead of individually (by each instruction in

the sequence) Example:

Drive_To_Uni

Procedure – following a sequence….Example

procedure Drive_To_Uni { 1. find car keys 2. disable car alarm 3. open car door 4. get in car 5. shut car door 6. put keys in ignition 7. start car 8. back car out of

driveway 9. drive to end of street 10. turn right 11. drive to end of street 12. turn left ...etc...etc...etc

...etc...etc...etc...

52. find parking space

53. pull into parking space

54. turn off engine

55. remove keys from ignition

56. open car door

57. get out

58. shut car door

59. lock car door

60. enable alarm

}

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_CS100_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

procedure Do_Week

{

Do_Monday

Do_Tuesday

Do_Wednesday

Do_Thursday

...etc...etc...etc...

}

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

In this subject, we also use the following words to refer to a “Procedure” :

Sub-routine Module Function

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

We use brackets to mark the beginning and end of a sequence.

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

An instruction invoking a procedure is known as a “procedure call”

Procedure A procedure may have a set of parameters

procedure customerService ( myName ,timeOfDay ){ say “Good timeOfDay” say “My name is myName” say “How can I help you?”}

customerService ( “Ali”, “Morning” )

customerService (“Jamil”, “Afternoon” )

customerService ( “Shah”, “Afternoon” )

Components of an Algorithm

Values and Variables Instruction (a.k.a. primitives) Sequence (of instructions) Procedure (involving instructions) Selection (between instructions) Repetition (of instructions) Documentation (beside instructions)

Selection

An instruction that decides which of two possible sequences is executed

The decision is based on a single true/false condition

Examples:Car repairReciprocals

Selection Example -- Car Repairif (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Selection Example –Car Repair..

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Should be a true or false condition.

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is true.

Selection Example –Car Repair..

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is false.

Selection Example –Car Repair..

Selection Example -- Reciprocals

Q. Give an algorithm for computing the reciprocal of a number.

Examples:

Reciprocal of 2: 1/2

Reciprocal of -3/4: 1/(-3/4) = -4/3

Reciprocal of 0: “undefined”

Selection Example – Reciprocals ..

Q. Give an algorithm for computing the reciprocal of a number.

Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else {

output "infinity" }

Selection Example-- Reciprocals

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Num is a variable whose value depends on the actual number the user provides.

Selection Example – Reciprocals…

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Condition depends on the value of Num

Selection Example – Reciprocals…

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

For a given value of Num, only one of these two sequences can be executed

Selection Example – Reciprocals…

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Executed if Num is not equal to 0

Selection Example – Reciprocals…

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Executed if Num is equal to 0

Selection -- Exercise

input Num if (Num is not equal 0) then { output 1/Num } else {

output "infinity" }

Will the following algorithms produce the same output?

Algorithm 1: input Num

if (Num is not equal 0)

then

{

output 1/Num

}

output "infinity"

Algorithm 2:

Selection – Several Conditions What if several conditions need to be

satisfied?if ( today is Wednesday and the time is 10.00am )

then

{

Go to CS100 Lecture

}

else

{

Go to Library

} Solution 1

Selection – Several Conditions..

Solution 2

Often called a “nested selection”

if ( today is Wednesday ) then {

if ( the time is 10.00am ) then { Go to CSE1301 Lecture } } else ...etc...etc...etc...

Selection – At Least One of Several Conditions What if at least one of several conditions

needs to be satisfied?

if ( I feel hungry or the time is 1.00pm or my friend has his eye on my lunch )

then

{

Eat my lunch now

}

Components of an Algorithm

Values and Variables Instruction (a.k.a. primitives) Sequence (of instructions) Procedure (involving instructions) Selection (between instructions) Repetition (of instructions) Documentation (beside instructions)

Repetition Repeat an instruction...

...while (or maybe until) some true or false condition occurs

Test the condition each time before repeating the instruction

Also known as iteration or loop Example:

Algorithm for getting a leave from the class.

Repetition -- Exampleprocedure getleave ( teacher, course, time)

{

reach_to(teacher)

Say(“Hello", teacher, “I am feeling fever!")

Say(“I want leave in ", course, "at", time, "?")

ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("please!")

add 1 to begging count

ListenToReply ( )}

}

Repetition – Example (cont)procedure getleave ( teacher, course, time){

reach_to(teacher)Say(“Hello", teacher, “I am feeling fever!")Say(“I want leave in ", course, "at", time, "?")ListenToReply ( )start begging count at zerowhile ( reply is "No" and begging count < 100 ){ Say("please!") add 1 to begging count ListenToReply ( )}

}

Condition is tested before sequence

Repetition – Example (cont)

procedure getleave ( teacher, course, time){

reach_to(teacher)Say(“Hello", teacher, “I am feeling fever!")Say(“I want leave in ", course, "at", time, "?")ListenToReply ( )start begging count at zero

while (reply is "No" and begging count < 100){ Say(“Please!") add 1 to begging count ListenToReply ( )}

}

Sequence may not get executed at all

Repetition – Example (cont)procedure getleave ( teacher, course, time){

reach_to(teacher)Say(“Hello", teacher, “I am feeling fever!")Say(“I want leave in ", course, "at", time, "?")

ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say(“Please!") add 1 to begging count ListenToReply ( )}

}

Ensure initial values of variables used in the conditions are set correctly

Repetition – Example (cont)

procedure getleave ( teacher, course, time){

reach_to(teacher)Say(“Hello", teacher, “I am feeling fever!")Say(“I want leave in ", course, "at", time, "?")ListenToReply ( )start begging count at zero

while (reply is "No" and begging count < 100){ Say(“Please!") add 1 to begging count ListenToReply ( )}

}

Ensure the variables used in the conditions are updated in each iteration

Repetition – Example (cont)

procedure getleave ( teacher, course, time)

{

reach_to(teacher)

Say(“Hello", teacher, “I am feeling fever!")

Say(“I want leave in ", course, "at", time, "?")

ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("please!")

}

}Infinite loop

• What if we don’t increment the begging count?

Documentation Records what the algorithm does Describes how it does it Explains the purpose of each component

of the algorithm Notes restrictions or expectations Example:

Getting a leave (again)

Components of an Algorithm

Values and Variables Instruction (a.k.a. primitives) Sequence (of instructions) Procedure (involving instructions) Selection (between instructions) Repetition (of instructions) Documentation (beside instructions)

The Software Development Process

We have covered this topic in Lecture 7 “Database systems”.Same process is followed to develop a

computer program.

Top-down Algorithm Design Write down what you have to do Break that into 3-7 smaller steps Break each step into 3-7 smaller steps Keeping subdividing until each individual

step is easy enough to do – i.e., until it is a single instruction

Example:Learning

Top-down Design -- Example

Learn

Prepare

Study

Reinforce

ReadMake notesPrepare questions

Attend lectureListen and thinkComplete pracAttend tute

Record answers to questions

Revise notes

Read lecture notesRead textbook

Read exerciseDesign algorithmCode solutionTest and document

Record insights

Summary Programming is the way to instruct the computer

what to do? Users set of computer instructions to be executed by

the computer. Different levels of programming exists. Algorithms are developed before making a

program to set a procedure. Remember “Computers are stupid” means you

need to teach them step by step each and every instruction, they can not do it by themselves.