Upload
anis-richardson
View
220
Download
0
Embed Size (px)
Citation preview
Programming and Problem SolvingWith Java
Copyright 1999, James M. Slack
IntroductionWhat is a Computer?Programming a ComputerTypes of Computer SystemsHistory of ComputersThe Software CrisisProgramming Languages
Programming and Problem Solving with Java 2
What is a Computer?Computer is a machine
Has partsRuns on electricityBreaks down sometimes
What makes it different from other machines?Can follow a list of instructions Instructions process symbols
Therefore
A computer isan information-processing
machine
Programming and Problem Solving with Java 3
What is a Computer?Computer follows a list of instructions one
instruction at a timeStart with first instructionDo each next instruction in turnStop when last instruction reached
Similar to how you follow a list of instructions...
Programming and Problem Solving with Java 4
What is a Computer?Example of following instructions - assemble a bike
Right Pedal1. Find the pedal with an "R" marked on the end of the threads.2. Insert the threads into the opening on the crank on the right side of the bicycle.3. Twist the threads into the crank by hand in a clockwise direction.4. Tighten the threads securely with a 5/8-inch open-end wrench.
Left PedalFollow the same assemblyinstructions for the right pedal (above) but twist the threads in a counterclockwise direction.
Pedal
Crank
Threads
Programming and Problem Solving with Java 5
What is a Computer?Kinds of instructions a computer can follow (in one
step) “Add the numbers 16 and 23”
Kinds of instructions a computer can’t follow (in one step) “Balance my checkbook”
What’s the difference?Computer instructions are simple (add 2 numbers,
subtract one number from another)Must combine thousands of computer instructions in a
program to do more complex tasks
Programming and Problem Solving with Java 6
What is a Computer?Kinds of computer instructions
Arithmetic: add, subtract, multiply, divideComparison: compare two numbers to see which is
greater, or whether the two numbers are equal or notBranching: jump to some other instruction in the
program (list of instructions) and continue processing from there
A computer can execute millions of these simple instructions each second
Programming and Problem Solving with Java 7
What is a Computer?Major parts of a computer
InputDevice
CentralProcess ing Unit
(CPU)
PrimaryMemory
OutputDevice
SecondaryMemory
Programming and Problem Solving with Java 8
What is a Computer?A vending machine
is like acomputer
M e m oryA m ount in s toc kA m ount of c hange
P roce ssin gChec k if in s toc kDeliver itemCom pute c hange
SnacksIn s e r tc o in s
M a k es e le c ti o n
C h a n g e
Inp ut de vice sCoin s lotS elec t ion buttons
O u tp ut de vice sChange s lotDelivery t ray
Programming and Problem Solving with Java 9
What is a Computer?Common input and output devices
Mon ito r( ou tpu t)
K e y bo ar d( inpu t)
Mo us e( inpu t)
S y s tem un it
Pr in te r( ou tpu t)
Programming and Problem Solving with Java 10
What is a Computer?Central Processing Unit (CPU)
Most important part of the computerFollows instructions
Important characteristicsClock speed
•How fast the computer switches between 2 on states or 2 off states•Early 80’s: 5,000,000 times per second (5 MHz)•Today: 400,000,000 to 1,000,000,000 and up! (400 MHz to 1 GHz)
Instruction set•The set of machine language instructions the CPU understands•Examples: Intel Pentium, Motorola PowerPC, IBM AS/400•Some CPUs understand machine language instructions of others -- AMD and Cyrix chips understand Intel Pentium instructions
Programming and Problem Solving with Java 11
What is a Computer?Subcomponents of a CPU
The arithmetic/logic unit, or ALU: does addition, subtraction, and other arithmetic operations, and also compares values
The control unit. determines which instruction to execute next
A small number of registers. each is a high-speed storage area for temporary results
Programming and Problem Solving with Java 12
What is a Computer?Types of Computer Memory
PrimarySecondary
Primary MemoryConnected directly to the CPUUsually called RAM (random-access memory)Usually loses contents when power switched off --
volatile
Programming and Problem Solving with Java 13
What is a Computer?Secondary Memory
Disks, tapes, floppy disks Is sometimes removableMuch cheaper than primary memorySlower than primary memoryKeeps contents when power switched off -- non-volatile
(a)
(b)
Programming and Problem Solving with Java 14
What is a Computer?Types of Computer Memory
Feature Primary Memory Secondary Memory
Speed (transfer rate) 10 to 200 megabytes/second 1 to 20 megabytes/second (harddisk)
Volatile (loses contentswithout power)
Yes No
Size Tens or hundreds ofmegabytes
Thousands of megabytes
Cost $2/megabyte $0.01/megabyte
Programming and Problem Solving with Java 15
What is a Computer?Primary Memory
Can imagine as sequence of cellsEach cell has a memory addressFirst cell is memory address 0
Memoryc e ll0
Memoryc e ll1
Memoryc e ll2
Programming and Problem Solving with Java 16
What is a Computer?Primary Memory
Each memory cell stores a single value, such as a small number
If you put a new value into a memory cell, the old contents is lost
2 1 0
(a) (b)
Memoryc ell
1002
Memoryc ell
1002
1 4 5 2 1 0
Programming and Problem Solving with Java 17
What is a Computer?Primary Memory
Can retrieve the contents of a cell without losing the contents
210(a) (b)
M e m o ryc e l l
1 0 0 2
M e m o ryc e l l
1 0 0 2
210210
Programming and Problem Solving with Java 18
What is a Computer?Secondary Memory
Information clustered in files File: collection of related
information Each file has a name Example: NAMES.DAT,
Balance.java
Files a re s to red inr ings c alled trac ks
Magneticrec ordings ur f ac e
Read/w r itehead
Programming and Problem Solving with Java 19
Programming a ComputerHow we solve most problems without a computer
Analyze the problem, come up with a solution
P roblemS tatem ent
P roblemS olution
Programming and Problem Solving with Java 20
Programming a ComputerHow we can get the
computer to solve a problem Must come up with
an algorithm (series of steps)
Computer follows the steps to solve the problem
P roblemS tatem ent
P roblemS olution
A lgorithmto s olveP roblem
(P rogram )
Programming and Problem Solving with Java 21
Programming a ComputerAlgorithm
Steps that a computer can follow to solve a problemHoliday Cookies1 cup sugar 1/4 tsp. ginger3/4 cup shortening 1 tsp. cinnamon1 cup dark corn syrup 1/2 tsp. nutmeg2 eggs 1/2 tsp. cloves1 lemon rind (grated) 2 tsp. anise seed3 cups flour 3/4 tsp. ground cardaman1 tsp. baking powder icing (powder sugar and water)1 tsp. baking soda colored sugar and candy decorations
1. Sift dry ingredients together in a large bowl and set aside.2. In another large bowl, use mixer to cream sugar and shortening together.3. Mix syrup, eggs, and lemon rind into sugar and shortening mixture.4. Add dry ingredients to mixture gradually.5. Refrigerate at least one hour to make handling easier.6. With rolling pin, roll out to 1/8-inch thickness on a floured surface, and cut with cookie cutters.7. Bake on greased cookie sheet 10-12 minutes at 375°F.8. Remove from cookie sheet and let cool to room temperature.9. Frost with icing, and decorate with colored sugar and candy.
Similar toa recipe
Programming and Problem Solving with Java 22
Programming a ComputerRecipe lists steps, but doesn’t say who is doing the
steps Implied that you (the cook) should do the stepsMany algorithms written this way -- structured approach
to programmingNew approach -- object-oriented programming
Consists of a set of cooperating objects trying to accomplish a goal
Each step says who (which object) should do that stepSimilar to the script for a play
Programming and Problem Solving with Java 23
Programming a ComputerTHE IMPORTANCE OF BEING EARNEST
by Oscar Wilde
The Persons of the Play
John Worthing, J.P. Lady BracknellAlgernon Moncrieff Hon. Gwendolen
FairfaxRev. Canon Chasuble, D.D. Cecily CardewMerriman, Butler Miss Prism,
GovernessLane, Manservant
The Scenes of the Play
Act I: Algernon Moncrieff's Flat in Half-Moon Street, W. Act II: The Garden at the Manor House, Woolton. Act III: Drawing-Room at the Manor House, Woolton
Programming and Problem Solving with Java 24
Programming a ComputerTHE IMPORTANCE OF BEING EARNEST (continued)
ACT ONESCENE. Morning-room in Algernon's flat in Half-Moon Street. The room is luxuriously and artistically furnished. The sound of a piano is heard in the adjoining room. (Lane is arranging afternoon tea on the table, and after the music has ceased, Algernon enters.) ALGERNON. Did you hear what I was playing, Lane? LANE. I didn't think it polite to listen, sir. ALGERNON. I'm sorry for that, for your sake. I don't play accurately-anyone can play accurately-but I play with wonderful expression. As far as the piano is concerned, sentiment is my forte. I keep science for life. LANE. Yes, sir. ALGERNON. And, speaking of the science of life, have you got the cucumber sandwiches cut for Lady Bracknell? LANE. Yes, sir. (Hands them on a salver.) ALGERNON. (Inspects them, takes two, and sits down on the sofa.) Oh! ... by the way, Lane, I see from your book that on Thursday night, when Lord Shoreman and Mr. Worthing were dining with me, eight bottles of champagne are entered as having been consumed. LANE. Yes, sir; eight bottles and a pint. ALGERNON. Why is it that at a bachelor's establishment the servants invariably drink the champagne? I ask merely for information.
Programming and Problem Solving with Java 25
Programming a ComputerTHE IMPORTANCE OF BEING EARNEST (continued)
LANE. I attribute it to the superior quality of the wine, sir. I have often observed that in married households the champagne is rarely of a first-rate brand. ALGERNON. Good Heavens! Is marriage so demoralizing as that? LANE. I believe it is a very unpleasant state, sir. I have had very little experience of it myself up to the present. I have only been married once. That was in consequence of a misunderstanding between myself and a young person. ALGERNON. (Languidly.) I don't know that I am much interested in your family life, Lane. LANE. No, sir; it is not a very interesting subject. I never think of it myself. ALGERNON. Very natural, I am sure. That will do, Lane, thank you. LANE. Thank you, sir. (Lane goes out.) ALGERNON. Lane's views on marriage seem somewhat lax. Really, if the lower orders don't set us a good example, what on earth is the use of them? They seem, as a class, to have absolutely no sense of moral responsibility. (Enter Lane.) LANE. Mr. Ernest Worthing. (Enter Jack. Lane goes out.)...
Programming and Problem Solving with Java 26
Programming a ComputerWhy is an object-oriented algorithm like a script?
Object-oriented algorithm simulates activities of several explicit actors
Each actor has specific steps to performEach actor free to use any appropriate technique to
accomplish its taskCombined effort of all these simulated actors results in
the goal of the algorithmCombined effort of real actors of a play results in
enjoyable entertainment
Programming and Problem Solving with Java 27
Programming a ComputerProgramming languages
Very formal language with strict rules about spelling and grammar
Need write algorithm in a programming language before running the algorithm on the computer
Many programming languagesWill use Java in this course
Programming and Problem Solving with Java 28
Programming a ComputerComputers understand machine language directly
Example: add 16 and 23 in Intel 8086 machine language1011 0000 0001 00000000 0100 0001 01111010 0010 0100 1000 0000 0000
1011 0000 0001 00000000 0100 0001 01111010 0010 0100 1000 0000 0000
OK ...
Programming and Problem Solving with Java 29
Programming a ComputerParts of machine language program step
First statement from example
Instruction says: Copy the number 16 into the AL register
Difficult to read and write machine language!
1011 0000 0001 0000
Copy informationto a register
Use theAL register
The number 16in binary (base 2)
Programming and Problem Solving with Java 30
Programming a ComputerAssembly language
One step up from machine languageEach assembly language instruction corresponds to one
machine language instruction
MOV AL,16D 1011 0000 0001 0000
ADD AL,23D 0000 0100 0001 0111
MOV [SUM],AL 1010 0010 0100 1000 0000 0000
Programming and Problem Solving with Java 31
Programming a ComputerAssembly language
Computer can’t understand assembly language directly
Must translate from assembly to machine language
Assembler: program that does this translation
MOV AL,16DADD AL,23DMOV [SUM],AL
Huh?
Ok ...
A s s embler1011 0000 0001 00000000 0100 0001 01111010 0010 0100 1000 0000 0000
MOV AL,16DADD AL,23DMOV [SUM],AL
Programming and Problem Solving with Java 32
Programming a ComputerHigh-level languages
Each high-level language instruction may correspond to several machine language instructions
Easier for people to read and write than assembly Java example:
(Note: Java usually translated to Java bytecodes, not Intel machine language...)
1011 0000 0001 0000
sum = 16 + 23; 0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
Programming and Problem Solving with Java 33
Programming a ComputerHigh-level languages
Must translate high-level language program to machine language before computer can execute it
Compiler: program that does this translation
Ok ...
Compiler1011 0000 0001 00000000 0100 0001 01111010 0010 0100 1000 0000 0000
sum = 16 + 23;
Programming and Problem Solving with Java 34
Programming a Computer: JavaThe Java Programming Language
A high-level language Java compiler translates to Java bytecodes for execution
on a Java Virtual Machine (JVM)
Ok ...
J a va V i r tu a lM a c h in e
T ra n s la to r
1011 0000 0001 00000000 0100 0001 01111010 0010 0100 1000 0000 0000
sum = 16 + 23;J a va
C o m p i l e r
J V MM a c h in e
L a n g u a g e
Programming and Problem Solving with Java 35
Programming a Computer: JavaAdvantage of Java Virtual Machine approach
Can run compiled Java program on any machine with a Java Virtual Machine installed
Makes compiled Java programs very portableDisadvantage
Takes more time -- Java programs run slower than programs compiled to machine code
BUT ... Today’s machines are so fast that the difference is not
noticeable for many programs
Programming and Problem Solving with Java 36
Programming a Computer: JavaKinds of Java programs
ApplicationsApplets
ApplicationsRun as stand-alone programsPrograms stored on the same machine they run onLike a text editor, word processor, spreadsheet, ...Can be graphical or console-based
AppletsRun inside a web browserPrograms stored on a web server, run on a client
machine
Programming and Problem Solving with Java 37
Programming a Computer: JavaExample Java program (application)
// This Java program finds the sum of 16 and 23,// then displays the result.
public class Add16And23{ public static void main(String[] args) { int sum;
sum = 16 + 23; System.out.println("The sum of 16 and 23 is " + sum); }}
Steps to run this programType the program text exactlySave the program in file Add16And23.javaCompile the program with a Java compilerRun program Add16And23.class with a JVM interpreter
Programming and Problem Solving with Java 38
Programming a Computer: JavaUse an editor that saves text files, such as MS-
DOS edit (in MS-DOS box)
Programming and Problem Solving with Java 39
Programming a Computer: JavaCompile the program
javac Add16And23.java
Run the programjava Add16And23
Result: program should displayThe sum of 16 and 23 is 39
$ javac Add16And23.java$ java Add16And23The sum of 16 and 23 is 39$
Unix display
Programming and Problem Solving with Java 40
Programming: DevelopmentExample program: display average of seriesFirst step: understand the problem
Where should program get the numbers? KeyboardHow does program know how many numbers? Will enter
0 at end of listWhere should program display result? On screen
Second step: come up with algorithmSolve problem yourself -- write down steps you tookResult is an algorithm
Programming and Problem Solving with Java 41
Programming: DevelopmentSteps for
finding average of series of numbers
StepNumber Action
Value ofinputdata
Value ofrunning
total
Value ofrunningcount
Value ofaverage
1 Set running total to 0 — 0 — —
2 Set running count to 0 — 0 0 —
3 Read a value 9 0 0 —
4 Check if value is 0 (stop reading if so) 9 0 0 —
5 Add value to running total 9 9 0 —
6 Add 1 to running count 9 9 1 —
7 Read a value 3.2 9 1 —
8 Check if value is 0 (stop reading if so) 3.2 9 1 —
9 Add value to running total 3.2 12.2 1 —
10 Add 1 to running count 3.2 12.2 2 —
11 Read a value 8 12.2 2 —
12 Check if value is 0 (stop reading if so) 8 12.2 2 —
13 Add value to running total 8 20.2 2 —
14 Add 1 to running count 8 20.2 3 —
15 Read a value 0 20.2 3 —
16 Check if value is 0 (stop reading if so) 0 20.2 3 —
17 Stop , because value is 0 0 20.2 3 —
18 Compute the average by dividing therunning total by the count
0 20.2 3 6.73
19 Display the average 0 20.2 3 6.73
Programming and Problem Solving with Java 42
Programming: DevelopmentConvert steps into an algorithm
Display the program's titleSet running total to 0.Set running count to 0.Repeat these steps:
•Read a value.•Check if value is 0 (stop this loop if so).•Add value to running total.•Add 1 to running count.
Compute the average by dividing the running total by the count.
Display the average.
Programming and Problem Solving with Java 43
Programming: DevelopmentConvert algorithm into program
// This program displays the average of a series of// numbers terminated by zero. The user enters the numbers using// the keyboard, and the average is displayed on the screen.
import java.io.*;import java.text.NumberFormat;
public class ComputeAverage{ public static void main(String[] args) throws java.io.IOException, java.text.ParseException { double inputValue; // Last value read from the user double runningTotal; // Total of all input values read so far int runningCount; // Count of all input values read so far double average; // Average of input values
// Create an input stream and attach it to the standard // input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
// Create a number formatter object NumberFormat formatter = NumberFormat.getInstance();
// Display the program title System.out.println("--- Compute Average ---");
// Set running total to 0 runningTotal = 0;
Programming and Problem Solving with Java 44
Programming: Development // Set running count to 0 runningCount = 0;
// Read the first input value System.out.print("Enter a value (0 to stop): "); System.out.flush(); inputValue = formatter.parse(inStream.readLine()).doubleValue();
// Keep reading until 0 while (inputValue != 0) { // Add value to running total runningTotal = runningTotal + inputValue;
// Add 1 to running count runningCount = runningCount + 1;
// Read the next input value System.out.print("Enter a value (0 to stop): "); System.out.flush(); inputValue = formatter.parse(inStream.readLine()).doubleValue(); }
// Compute the average average = runningTotal / runningCount;
// Display the average System.out.println("The average is " + average); }}
Programming and Problem Solving with Java 45
Programming: DevelopmentLast step: Make sure the program works correctly
First test -- ok--- Compute Average ---Enter a value (0 to stop): 9Enter a value (0 to stop): 3.2Enter a value (0 to stop): 8Enter a value (0 to stop): 0The average is 6.73333
Second test -- ok--- Compute Average ---Enter a value (0 to stop): 9.1Enter a value (0 to stop): 2.6Enter a value (0 to stop): 7.3Enter a value (0 to stop): 1.4Enter a value (0 to stop): 6.44Enter a value (0 to stop): 8Enter a value (0 to stop): 5.72Enter a value (0 to stop): 0The average is 5.79429
Third test -- not ok (doesn’t work if nothing to average)--- Compute Average ---Enter a value (0 to stop): 0The average is NaN
Programming and Problem Solving with Java 46
Programming: DevelopmentModified program
// This program displays the average of a series of// numbers terminated by zero. The user enters the numbers using// the keyboard, and the average is displayed on the screen.
import java.io.*;import java.text.NumberFormat;
public class ComputeAverage{ public static void main(String[] args) throws java.io.IOException, java.text.ParseException { double inputValue; // Last value read from the user double runningTotal; // Total of all input values read so far int runningCount; // Count of all input values read so far double average; // Average of input values
// Create an input stream and attach it to the standard // input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
// Create a number formatter object NumberFormat formatter = NumberFormat.getInstance();
// Display the program title System.out.println("--- Compute Average ---");
// Set running total to 0 runningTotal = 0;
Programming and Problem Solving with Java 47
Programming: Development // Set running count to 0 runningCount = 0;
// Read the first input value System.out.print("Enter a value (0 to stop): "); System.out.flush(); inputValue = formatter.parse(inStream.readLine()).doubleValue();
// Keep reading until 0 while (inputValue != 0) { // Add value to running total runningTotal = runningTotal + inputValue;
// Add 1 to running count runningCount = runningCount + 1;
// Read the next input value System.out.print("Enter a value (0 to stop): "); System.out.flush(); inputValue = formatter.parse(inStream.readLine()).doubleValue(); }
if (runningCount > 0) {
// Compute the average average = runningTotal / runningCount;
// Display the average System.out.println("The average is " + average); }
else System.out.println("Can't compute average: No input values");
}}
Changes
Programming and Problem Solving with Java 48
Programming: DevelopmentLast step: Test program again
First test -- ok--- Compute Average ---Enter a value (0 to stop): 9Enter a value (0 to stop): 3.2Enter a value (0 to stop): 8Enter a value (0 to stop): 0The average is 6.73333
Second test -- ok--- Compute Average ---Enter a value (0 to stop): 9.1Enter a value (0 to stop): 2.6Enter a value (0 to stop): 7.3Enter a value (0 to stop): 1.4Enter a value (0 to stop): 6.44Enter a value (0 to stop): 8Enter a value (0 to stop): 5.72Enter a value (0 to stop): 0The average is 5.79429
Third test -- ok--- Compute Average ---Enter a value (0 to stop): 0Can't compute average: No input values
Programming and Problem Solving with Java 49
Programming: DevelopmentSteps in program development
Understand the problemCome up with an algorithmWrite the programTest the program
Programming and Problem Solving with Java 50
Programming: DevelopmentUnderstand the problem
Need to understand problem thoroughly before beginning to write program
Tempting to start writing program before understanding problem -- probably single most common cause of errors in programs
How to understand the problemLook at input and output requirementsAsk people involved with the problem domainTry writing about the program -- write what it should do in
your own words
Programming and Problem Solving with Java 51
Programming: DevelopmentCome up with an algorithmAlgorithm is a series of steps, and it ...
is finite -- can’t have infinite series of steps is unambiguous -- must state precisely what to do at
each step is effective -- must do what it is supposed to towill terminate -- won’t go on forever
Programming and Problem Solving with Java 52
Programming: DevelopmentWrite the program
If you have an algorithm this step is mechanicalGets easier the more you learn and use Java
Desk checkingSimulate the action of the
computer in your mindGood time to do this is as
you write the program (you’re thinking about the program anyway)
Programming and Problem Solving with Java 53
Programming: DevelopmentTest the program
Try the program with sample dataMake sure to try several different samples (may work on
one set but not others)Don’t worry if it doesn’t work the first time -- professionals
rarely get it right the first time, either
Programming and Problem Solving with Java 54
Types of ComputersFour major types of computer systems
Single-user personal computerTime-sharing computerBatch computerNetwork computer system
Programming and Problem Solving with Java 55
Types of ComputersSingle-user personal computer
One person uses at a timeHas become popular since early 80’s Interactive -- computer responds
immediately to user commands
Programming and Problem Solving with Java 56
Types of ComputersTime-sharing computer
Many people can use simultaneouslyEach person uses a terminal
connected to the computer
Printer
Min ic omputer
Programming and Problem Solving with Java 57
Types of ComputersHow does time-sharing computer service many
people simultaneously?Only appears to act this wayActually does a little bit of work for each person in turnProcess is called pollingPolls so fast that it seems like the computer is serving
everyone at the same time
Programming and Problem Solving with Java 58
Types of ComputersBatch computer system
Not interactive -- must schedule work with computer operator
Operator schedules work so the computer can get the most work done in the shortest time
Advantage of batch: efficiencyUsed in large companies for repetitive tasks
Payroll, accounting, ...
Mainf ramePr inte r
Programming and Problem Solving with Java 59
Types of ComputersComputer network
Group of connected computersServer: fast, expensive computer that stores programs
and other files for the other computers (clients)Advantage of network vs. time-sharing
Each client is a computerResponse time is better
Des ktop c omputer Des ktop c omputer
Des ktop c omputer Des ktop c omputer
Dis k A rray Serv er
Pr inter
Programming and Problem Solving with Java 60
History of ComputersAbacus: oldest mechanical calculating aid
Invented in Babylon about 3000 years agoAlso used by ChineseEach wire represents a decimal position (ones, tens, ...)Can do addition, subtraction, multiplication and division
by moving beads on the strings
Programming and Problem Solving with Java 61
History of ComputersBlaise Pascal
Invented first mechanical calculator in 1642Did multiplication and division
Gottfried von LeibnitzExpanded Pascal's machine in 1671Handled multiplication, division, and square roots
Joseph-Marie Jacquard Invented loom that read tape of punched cards in 1801Wove cloth according to instructions on cardsFirst machine that could be reprogrammed
Programming and Problem Solving with Java 62
History of ComputersCharles Babbage
Designed Difference Engine (mid 1800’s)Supposed to compute and print mathematical tablesNever completed -- Babbage spent time designing
Analytical EngineDesigned to follow instructions in a program and thus
handle any computationWould store program on cards in the machine's memory --
this is the stored program conceptNever completed -- English government stopped the
fundingProbably wouldn’t have worked -- required metalworking
skills beyond what was possible at the time
Programming and Problem Solving with Java 63
History of ComputersAugusta Ada (later Countess of Lovelace)
World’s first computer programmerAssisted BabbageTranslated one of Babbage’s papers on Analytical Engine
from French to English (1842) In margins, she wrote examples of how to use the
machine -- program examples
Programming and Problem Solving with Java 64
History of ComputersHerman Hollerith
Invented method of using punched cards for automated data processing
US government used Hollerith's machines to tabulate the 1890 census
Hollerith's firm later merged with three other firms to become International Business Machines (IBM)
Punched cards used for tabulating and sorting information into the 1960's
Programming and Problem Solving with Java 65
History of ComputersHoward Aiken
Designed the Mark I computer -- the world's first automatic computer (1944)
Operated with electro-mechanical switchesAble to multiply two numbers together in six seconds
John W. Mauchly and J. Presper EckertDesigned ENIAC -- the first general-purpose electronic
computer (1946)Hundreds of times faster than any electro-mechanical
computing deviceProgrammed by plugging wires into holes along the
outside of the machine.
Programming and Problem Solving with Java 66
History of ComputersFirst generation computers (1950’s)
UNIVAC I (1951, Sperry-Rand): first commercial computer
Other companies soon followedComputers were bulky, unreliableUsed vacuum tubes for electronic switching (hot --
burned out often)Most programs
written in machine language
Used punched cards for data storage
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
12345
Programming and Problem Solving with Java 67
History of ComputersSecond generation computers (late 50’s -
mid 60’s)Started using transistors instead of vacuum
tubesComputers became more reliableFirst high-level languages (FORTRAN, COBOL,
Algol)Larger primary memoryMagnetic tapes used for long-term data storage
Programming and Problem Solving with Java 68
History of ComputersThird generation computers (mid 60’s to
early 70’s) IBM introduced System 360 line: every
machine in the line could run the same programs
Integrated circuits used: contains many transistors
Most computers ran in batch mode
Programming and Problem Solving with Java 69
History of ComputersFourth generation computers (early 70’s on)
Very large scale integration: hundreds, thousands, or millions of transistors on a single chip
Computers have become inexpensive and reliableTime-sharing popular in 1970’s and 1980’sToday, single-user personal computers are popularThe Internet connects many computers in a world-wide
computer network
Programming and Problem Solving with Java 70
Software CrisisHardware vs. software
Hardware: physical parts of the computerSoftware: computer programs
Advances in hardware have been spectacularFast, affordable computer systemsComputers in everyday appliances
Advances in softwareHave been many significant advances (high-level
languages, compilers, object-oriented programming, modern design techniques, ...)
Still need to do more though...
Programming and Problem Solving with Java 71
Software CrisisToday, many programs are
Expensive: they cost much more than initial projectionsUnreliable: they have serious errors which cause them
to work incorrectlyLate: they are delivered months or years after they're
promisedThis is a crisis ...
Programming and Problem Solving with Java 72
Software CrisisAbstraction
Ignore details, concentrate on essential featuresMost powerful tool to solve the software crisis
Levels of abstractionSometimes, details at one level become essential
features at another levelExample: stereo
•Consumer level: concentrate on tuner, CD player, tape desk, speakers, amplifier•Stereo designer: concentrate on circuits,discrete parts, chips•Chip designer: concentrate on circuitswithin the chip
Programming and Problem Solving with Java 73
Software CrisisUse abstraction when writing computer program
Programmer gives a name to each part of the programWhen working within the part, programmer concentrates
on the steps within that partWhen working outside the part, programmer thinks of the
part by its name (ignores the steps within)Usually several levels of abstraction in a computer
programMethod: most detailed levelClass: consists of several methods (and other things...)Package: consists of several classesSystem of packages: consists of several packages
Programming and Problem Solving with Java 74
Programming LanguagesHundreds of high-level programming languages
No best programming language for all usesSome are better than others for certain uses
Four major groupsProceduralFunctionalLogicObject-oriented
Programming and Problem Solving with Java 75
Languages: ProceduralProcedural languages
Largest group of languagesAlso called imperative languagesProgram consists of list of statements
VariablesProgram stores temporary values in variables, and can
change the value of a variableDifferent from mathematics: once we have chosen the
value of a variable, it remains fixed throughout the expression
x y / 3
Programming and Problem Solving with Java 76
Languages: ProceduralBASIC (Beginner’s All-purpose Symbolic Instruction
Code) Popular language for beginnersSimple syntax (originally only 14 statement types)Can run on small computersExample
10 REM THIS BASIC PROGRAM FINDS THE SUM OF20 REM 16 AND 23, THEN DISPLAYS THE RESULT.30 LET SUM = 16 + 2340 PRINT "The sum of 16 and 23 is ", SUM50 END
Microsoft Visual BASICMuch more sophisticated version of BASICFull-fledged development system for Microsoft Windows
Programming and Problem Solving with Java 77
Languages: ProceduralCOBOL (COmmon Business Oriented Language)
Most commonly used language in businessDesigned for ease of data movementExample
IDENTIFICATION DIVISION. PROGRAM-ID. ADDNUMS. AUTHOR. SLACK. DATE-WRITTEN. JUL 11,1997. DATE-COMPILED. JUL 12,1997.* THIS COBOL PROGRAM FINDS THE SUM* OF 16 AND 23, THEN DISPLAYS THE RESULT. ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. IBM-370. OBJECT-COMPUTER. IBM-370. DATA DIVISION. WORKING-STORAGE SECTION. 77 TOTAL PICTURE 99. PROCEDURE DIVISION. ADD 16, 23 GIVING TOTAL. DISPLAY 'THE SUM OF 16 AND 23 IS ', TOTAL UPON CONSOLE. STOP RUN.END PROGRAM
Programming and Problem Solving with Java 78
Languages: ProceduralFORTRAN (FORmula TRANslator)
The first high-level languagePopular with scientists and engineers (although many
engineers are switching to C and C++ today)Example
PROGRAM ADDNUMSC THIS FORTRAN PROGRAM FINDS THE SUM OFC 16 AND 23, THEN DISPLAYS THE RESULT.
INTEGER SUM SUM = 16 + 23 WRITE (*, 10) SUM 10 FORMAT ('THE SUM OF 16 AND 23 IS ', I2) STOP END
Programming and Problem Solving with Java 79
Languages: ProceduralC
Popular with programmers who write system-level code (operating systems, compilers, ...)
Example/* This C program finds the sum of 16 and 23, then displays the result. */
#include <stdio.h>
void main(void){ int sum; sum = 16 + 23; printf("The sum of 16 and 23 is %d\n", sum);}
Programming and Problem Solving with Java 80
Languages: ProceduralPascal (named after Blaise Pascal)
Designed as a simple alternative to Algol (another early programming language)
Used extensively to teach programming until the early 1990’s
ExamplePROGRAM AddNums (Input, Output);
{ This Pascal program finds the sum of 16 and 23, then displays the result. }
VAR Sum : Integer;
BEGIN Sum := 16 + 23; writeLn ('The sum of 16 and 23 is ', Sum)END.
Programming and Problem Solving with Java 81
Languages: FunctionalFunctional languages
Based on mathematical functionsProgram consists of functions and function callsNo variables in a pure functional language
LispMost popular functional languageUsed widely in artificial intelligence (especially in the US)Example
; This Lisp program finds the; sum of 23 and 16, then displays the result.(progn (let (Sum) (setq Sum (+ 23 16)) (princ "The sum of 23 and 16 is ") (princ Sum) ))
Programming and Problem Solving with Java 82
Languages: LogicLogic languages
Based on formal rules of logic and inferenceOnce set, program can't change value of a variableProgram consists of a set of known facts, plus rules for
inferring new facts from the existing facts
Programming and Problem Solving with Java 83
Languages: LogicProlog
Most popular logic languageUsed widely in artificial intelligence (especially in Europe
and Japan)Example
/* This Prolog program finds the sum of 16 and 23, then displays the result. */
run :- Sum is 16 + 23, write ("The sum of 16 and 23 is ", Sum), nl.
Programming and Problem Solving with Java 84
Languages: LogicAnother example of Prolog
/* Shows Prolog's inference ability */
likes(tom, pizza).likes(tom, apple).likes(jill, taco).likes(jill, apple).likes(bob, beans).likes(bob, apple).likes(jody, Food) :- likes(jill, Food), likes(bob, Food).
Run program by writing a queryExample
Goal: likes(jill, Food)Food=tacoFood=apple2 Solutions
Can also infer solutions based on known factsGoal: likes(jody, Food)Food=apple1 Solution
Programming and Problem Solving with Java 85
Languages: Object-orientedObject-oriented languages
Model each real-world entity as an objectEach object has set of values and behaviorsEach object is therefore active, because it has behaviors
Simula (Simulation language)First object-oriented language (1967)
SmalltalkFirst pure object-oriented language (early 1980’s)Everything in the language is an object
Programming and Problem Solving with Java 86
Languages: Object-orientedC++
Introduced in the mid 1980’sBased on the C languageHybrid language: procedural & object-orientedExample:
// This C++ program finds the sum of 16 and 23,// then displays the result.
#include <iostream.h>
void main(void){ int sum; sum = 16 + 23; cout << "The sum of 16 and 23 is " << sum << endl;}
Programming and Problem Solving with Java 87
Languages: Object-orientedJava
Introduced in 1995 by Sun MicrosystemsObject-oriented language, but not as pure as Smalltalk
•In Java, primitive values (numbers, characters) are not objects -- they are values•In Smalltalk, everything is an object
During its research, was designed for use in appliancesReleased version designed for use on the Internet and as
a general-purpose programming languageProbably the most famous programming language of all
time•Lots of coverage in regular news, unlike other programming languages•Huge excitement about the language