university of pittsburgh computer science 1 week 2: introduction welcome to those who were not here...

24
University of Pittsburgh Comp uter Science 1 Week 2: Introduction Week 2: Introduction Welcome to those who were not Welcome to those who were not here last week here last week Last week we discussed Last week we discussed Computer hardware and software Computer hardware and software Programming languages Programming languages Machine language Machine language High-level languages High-level languages Features of high-level languages Features of high-level languages Variables (single and arrays) Variables (single and arrays) Operations on variables Operations on variables

Upload: elfrieda-parrish

Post on 11-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

1

Week 2: IntroductionWeek 2: Introduction

• Welcome to those who were not Welcome to those who were not here last weekhere last week

• Last week we discussedLast week we discussed Computer hardware and softwareComputer hardware and software

Programming languagesProgramming languages Machine languageMachine language High-level languagesHigh-level languages

Features of high-level languagesFeatures of high-level languages Variables (single and arrays)Variables (single and arrays) Operations on variablesOperations on variables

Page 2: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

2

Week 2: IntroductionWeek 2: Introduction

Control structuresControl structures

Example programs using a Stack typeExample programs using a Stack type Push on the topPush on the top Pop from the topPop from the top We finished the implementationWe finished the implementation

Page 3: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

3

Week 2: IntroductionWeek 2: Introduction

• How can we improve our HLLs?How can we improve our HLLs? Complex programs can get HUGEComplex programs can get HUGE

Millions of lines of codeMillions of lines of code

This can lead to some problemsThis can lead to some problems The human mind works best when a problem is The human mind works best when a problem is

not too largenot too large– Ex. SSN, phone numbers, SIMON, shopping listsEx. SSN, phone numbers, SIMON, shopping lists

Many large projects require a team of programmersMany large projects require a team of programmers– How to divide the work, check the results?How to divide the work, check the results?

Programs' specs sometime changePrograms' specs sometime change– How will change affect the rest of the code?How will change affect the rest of the code?

I may have to do the same thing in different placesI may have to do the same thing in different places– Why rewrite the code? (ex. walk the dog)Why rewrite the code? (ex. walk the dog)

Page 4: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

4

Week 2: SubprogramsWeek 2: Subprograms

• Solution: break our programs into Solution: break our programs into SUBPROGRAMSSUBPROGRAMS A group of declarations and instructions A group of declarations and instructions

that functions similarly to a program, but that functions similarly to a program, but that cannot run by itselfthat cannot run by itself

• How do subprograms work?How do subprograms work? We We DECLAREDECLARE them somewhere in our code them somewhere in our code

We We CALLCALL them when we want them to execute them when we want them to execute

Page 5: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

5

Week 2: SubprogramsWeek 2: Subprograms

• When a subprogram is calledWhen a subprogram is called:: The code for the subprogram executesThe code for the subprogram executes

This may be in a different place than the main This may be in a different place than the main program codeprogram code

• When a subprogram finishesWhen a subprogram finishes:: The main program resumes at the next The main program resumes at the next

instruction after the subprogram callinstruction after the subprogram call

Page 6: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

6

Week 2: SubprogramsWeek 2: Subprograms

• Real life example:Real life example:

Let's see what

I need to do today...

Water the garden

Feed the cat

Play tennis

Fix the sidewalk Water ski

Feed the cat

Page 7: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

7

Week 2: SubprogramsWeek 2: Subprograms

• What does each of these really mean?What does each of these really mean?

Water the garden:

•Unwind hose•Turn on water•Spray until wet•Turn off water•Wind up hose

Feed the cat:•Open food•Put some into dish•Refill water•Reseal food

Page 8: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

8

Week 2: SubprogramsWeek 2: Subprograms

• What we are doing is What we are doing is REFININGREFINING our our taskstasks At the highest level we only are At the highest level we only are

concerned with what the tasks areconcerned with what the tasks are

When doing the tasks we need to know When doing the tasks we need to know each step involvedeach step involved

• We do the same thing with programsWe do the same thing with programs From main program we just need to know From main program we just need to know

the subprograms calledthe subprograms called

Within the subprograms we have the Within the subprograms we have the precise instructions that need to executeprecise instructions that need to execute

Page 9: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

9

Week 2: SubprogramsWeek 2: Subprograms

• Let's look at a simple exampleLet's look at a simple example Download, compile and run Seuss1.java Download, compile and run Seuss1.java

from the Exercises pagefrom the Exercises page

Page 10: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

10

Week 2: ParametersWeek 2: Parameters

• Usually we need our subprograms to Usually we need our subprograms to communicate with the main programcommunicate with the main program Ex. Building a houseEx. Building a house

General contractor has subcontractors to do General contractor has subcontractors to do the electrical, plumbing, masonry, etc.the electrical, plumbing, masonry, etc.

General contractor needs to talk to the subcontractors General contractor needs to talk to the subcontractors regarding scheduling, any problems, etc.regarding scheduling, any problems, etc.

Something learned from one subcontractor Something learned from one subcontractor may affect how another subcontractor worksmay affect how another subcontractor works– Pipes have been movedPipes have been moved– Subfloor is not installed yetSubfloor is not installed yet

• We accomplish this communication We accomplish this communication in programs with in programs with PARAMETERSPARAMETERS

Page 11: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

11

Week 2: ParametersWeek 2: Parameters

• ParametersParameters We can think of these as messages that are We can think of these as messages that are

passed from the main to the subs (and passed from the main to the subs (and possibly back to the main)possibly back to the main)

When a subprogram is called, the parameters When a subprogram is called, the parameters passed to the subprogram are called passed to the subprogram are called ARGUMENTSARGUMENTS

The subprogram uses these to help do it's jobThe subprogram uses these to help do it's job

See Seuss2.javaSee Seuss2.java Download from Exercises pageDownload from Exercises page Compile and run itCompile and run it Add another verse to itAdd another verse to it

Page 12: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

12

Week 2: How Subprograms WorkWeek 2: How Subprograms Work

• When a subprogram is calledWhen a subprogram is called Arguments are passed to itArguments are passed to it

Data for it is Data for it is pushpushed onto the ed onto the RUN-TIME STACKRUN-TIME STACK Stack works just as we discussed last weekStack works just as we discussed last week

Code for subprogram starts to executeCode for subprogram starts to execute

• Why do we need a stack for the data?Why do we need a stack for the data? A subprogram can call another subprogramA subprogram can call another subprogram

We need to keep track of the data for each We need to keep track of the data for each subprogram that has been calledsubprogram that has been called When "top" subprogram finishes, the next one When "top" subprogram finishes, the next one

down (new top) should resumedown (new top) should resume

Page 13: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

13

Week 2: RecursionWeek 2: Recursion

• The run-time stack also allows us to use The run-time stack also allows us to use RECURSIONRECURSION in our programs in our programs A subprogram calls itselfA subprogram calls itself

Quite mathematical in nature -- some common Quite mathematical in nature -- some common math problems can be defined recursivelymath problems can be defined recursively N!N!

Common solution: N! = N x (N-1) x (N-2) … x 1Common solution: N! = N x (N-1) x (N-2) … x 1

Recursive solution:Recursive solution:N! = N x (N-1)!N! = N x (N-1)! when N > 0when N > 0 recursive caserecursive caseN! = 1N! = 1 when N = 0when N = 0 base casebase case

Page 14: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

14

Week 2: RecursionWeek 2: Recursion

NNMM

Common solution: NCommon solution: NM M = N x N x N x … x N -> M times= N x N x N x … x N -> M times

Recursive solution:Recursive solution:NNMM = N x N = N x N(M-1)(M-1) when M > 0when M > 0 recursive caserecursive caseNNMM = 1 = 1 when M = 0when M = 0 base casebase case

• Concept seems difficultConcept seems difficult But can be usefulBut can be useful

Some famous algorithms are defined Some famous algorithms are defined recursivelyrecursively Sorting (QuickSort, MergeSort)Sorting (QuickSort, MergeSort) Searching (Binary Search)Searching (Binary Search) Image processing (Fast-Fourier Transform)Image processing (Fast-Fourier Transform)

Page 15: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

15

Week 2: RecursionWeek 2: Recursion

• Let's look at another famous exampleLet's look at another famous example Not very useful, but famous anywayNot very useful, but famous anyway

Good example of a problem that is VERY Good example of a problem that is VERY DIFFICULT to solve WITHOUT recursionDIFFICULT to solve WITHOUT recursion

• Towers of Hanoi problemTowers of Hanoi problem We have 3 towersWe have 3 towers

On first tower we have disks of decreasing sizeOn first tower we have disks of decreasing size

Goal is to get all disks onto last tower, butGoal is to get all disks onto last tower, but We can only move one disk at a timeWe can only move one disk at a time We can never put a larger disk on top of a smaller We can never put a larger disk on top of a smaller

oneone

Page 16: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

16

Week 2: RecursionWeek 2: Recursion

• Download Hanoi.java from Web siteDownload Hanoi.java from Web site Compile it and then run itCompile it and then run it

First try playing it yourself for a whileFirst try playing it yourself for a while Start with only 3 or 4 disks, then try moreStart with only 3 or 4 disks, then try more

Then let the computer solve it for youThen let the computer solve it for you You can go up to 10 disksYou can go up to 10 disks Adjust the delay so you can see each step for just Adjust the delay so you can see each step for just

a few disks (make it 1000 or more)a few disks (make it 1000 or more) For more disks make the delay small (50 or less) For more disks make the delay small (50 or less)

so the demo will finish in a reasonable amount of so the demo will finish in a reasonable amount of timetime

When you are done playing, we will look at When you are done playing, we will look at the code for a bitthe code for a bit

Page 17: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

17

Week 2: Subprogram SummaryWeek 2: Subprogram Summary

• In summary, subprograms give usIn summary, subprograms give us Smaller code piecesSmaller code pieces

Each piece not so complexEach piece not so complex

Reusable piecesReusable pieces I can call a subprogram many times from the same I can call a subprogram many times from the same

programprogram I can use the same subprogram in many programsI can use the same subprogram in many programs

Relatively independent piecesRelatively independent pieces Easier to debug themEasier to debug them Easier to add new pieces and to change the old Easier to add new pieces and to change the old

ones without "breaking" the rest of themones without "breaking" the rest of them Easier to teams to work on different piecesEasier to teams to work on different pieces

Page 18: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

18

Week 2: Subprogram SummaryWeek 2: Subprogram Summary

Procedural abstractionProcedural abstraction What is that?What is that? Idea: I can use a subprogram without Idea: I can use a subprogram without

necessarily knowing the details of how it worksnecessarily knowing the details of how it works– I should probably know its input, output and its I should probably know its input, output and its

general purpose, but that's allgeneral purpose, but that's all

Ex: y = sqrt(x)Ex: y = sqrt(x)– Calculate the square rootCalculate the square root– I know what that isI know what that is– I know it is a real numberI know it is a real number– I don't care how the computer actually does it!I don't care how the computer actually does it!

» Unless I was the one who had to write the codeUnless I was the one who had to write the code

Page 19: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

19

Week 2: Data Abstraction and OOPWeek 2: Data Abstraction and OOP

We can expand this idea to include We can expand this idea to include DATA DATA ABSTRACTIONABSTRACTION I don't need to know the implementation I don't need to know the implementation

details of a data type in order to use itdetails of a data type in order to use it

Ex. Stack from last weekEx. Stack from last week– If we know what push and pop MEAN, we don't If we know what push and pop MEAN, we don't

really have to know how they are implementedreally have to know how they are implemented– In fact a Stack can be implemented in various waysIn fact a Stack can be implemented in various ways– We only saw one of them last weekWe only saw one of them last week– No matter how it is implemented, it still functions No matter how it is implemented, it still functions

as a Stack in the same wayas a Stack in the same way

Data abstraction is one important part of Data abstraction is one important part of OBJECT-ORIENTED PROGRAMMINGOBJECT-ORIENTED PROGRAMMING

Page 20: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

20

Week 2: Object-Oriented ProgrammingWeek 2: Object-Oriented Programming

• OOP componentsOOP components Encapsulation/Data AbstractionEncapsulation/Data Abstraction

The DATA and OPERATIONS for a type are The DATA and OPERATIONS for a type are encapsulated together into an OBJECTencapsulated together into an OBJECT

Ex: StackEx: Stack– Operations: Push, Pop (and others)Operations: Push, Pop (and others)– Data: array of integers (or other data) Data: array of integers (or other data)

Ex: PersonEx: Person– Operations: Walk, talk, eat, sleepOperations: Walk, talk, eat, sleep– Data: body, name, address, ssn Data: body, name, address, ssn

Look at Hanoi.java againLook at Hanoi.java again– class Towerclass Tower

Page 21: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

21

Week 2: Object-Oriented ProgrammingWeek 2: Object-Oriented Programming

InheritanceInheritance Allows new classes to get all of the attributes of Allows new classes to get all of the attributes of

previously defined classespreviously defined classes Allows related classes to be accessed in a Allows related classes to be accessed in a

consistent wayconsistent way

Page 22: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

22

Week 2: Object-Oriented ProgrammingWeek 2: Object-Oriented Programming

PolymorphismPolymorphism Allows the same operation name to be defined Allows the same operation name to be defined

differently for different classesdifferently for different classes

move()

move()move() move()

move()

Page 23: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

23

Week 2: Object-Oriented ProgrammingWeek 2: Object-Oriented Programming

We may look at object-oriented We may look at object-oriented programming in more detail in a lab programming in more detail in a lab session latersession later

Page 24: University of Pittsburgh Computer Science 1 Week 2: Introduction Welcome to those who were not here last weekWelcome to those who were not here last week

University of Pittsburgh Computer Science

24

Week 2: SummaryWeek 2: Summary

• This week we discussedThis week we discussed Reasons for using subprogramsReasons for using subprograms

How subprograms workHow subprograms work Calling a subprogramCalling a subprogram ParametersParameters

RecursionRecursion Wacky!Wacky!

Object-oriented ProgrammingObject-oriented Programming EncapsulationEncapsulation InheritanceInheritance PolymorphismPolymorphism