Download program - Cengage Learning

Document related concepts
no text concepts found
Transcript
Programming and Problem Solving
With Java
Introduction
What is a Computer?
Programming a Computer
Types of Computer Systems
History of Computers
The Software Crisis
Programming Languages
Copyright 1999, James M. Slack
What is a Computer?
Computer is a machine
Has parts
Runs on electricity
Breaks down sometimes
What makes it different from other machines?
Can follow a list of instructions
Instructions process symbols
Therefore
Programming and Problem Solving with Java
A computer is
an information-processing
machine
2
What is a Computer?
Computer follows a list of instructions one
instruction at a time
Start with first instruction
Do each next instruction in turn
Stop when last instruction reached
Similar to how you follow a list of instructions...
Programming and Problem Solving with Java
3
What is a Computer?
Example of following instructions - assemble a bike
Right Pedal
1. 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.
Threads
Left Pedal
Follow the same assembly
instructions for the right pedal
(above) but twist the threads
in a counterclockwise direction.
Crank
Programming and Problem Solving with Java
Pedal
4
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
5
What is a Computer?
Kinds of computer instructions
Arithmetic: add, subtract, multiply, divide
Comparison: compare two numbers to see which is
greater, or whether the two numbers are equal or not
Branching: 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
6
What is a Computer?
Major parts of a computer
Central
Process ing Unit
(CPU)
Input
Device
Primary
Memory
Programming and Problem Solving with Java
Output
Device
Secondary
Memory
7
What is a Computer?
A vending machine
is like a
computer
Snacks
In s e rt
co in s
Input devices
Coin slot
Selection buttons
Ma ke
s e le ctio n
Change
Processing
Check if in stock
Deliver item
Compute change
Programming and Problem Solving with Java
Output devices
Change slot
Delivery tray
Memory
Amount in stock
Amount of change
8
What is a Computer?
Common input and output devices
Monitor
(output)
Printer
(output)
System unit
Keyboard
(input)
Mouse
(input)
Programming and Problem Solving with Java
9
What is a Computer?
Central Processing Unit (CPU)
Most important part of the computer
Follows instructions
Important characteristics
Clock 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
10
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
11
What is a Computer?
Types of Computer Memory
Primary
Secondary
Primary Memory
Connected directly to the CPU
Usually called RAM (random-access memory)
Usually loses contents when power switched off -volatile
Programming and Problem Solving with Java
12
What is a Computer?
Secondary Memory
Disks, tapes, floppy disks
Is sometimes removable
Much cheaper than primary memory
Slower than primary memory
Keeps contents when power switched off -- non-volatile
(b)
(a)
Programming and Problem Solving with Java
13
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 (hard
disk)
Volatile (loses contents
without power)
Yes
No
Size
Tens or hundreds of
megabytes
Thousands of megabytes
Cost
$2/megabyte
$0.01/megabyte
Programming and Problem Solving with Java
14
What is a Computer?
Primary Memory
Can imagine as sequence of cells
Each cell has a memory address
First cell is memory address 0
Memory
cell
0
Programming and Problem Solving with Java
Memory
cell
1
Memory
cell
2
15
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
(a)
(b)
210
145
Memory
cell
1002
Programming and Problem Solving with Java
210
Memory
cell
1002
16
What is a Computer?
Primary Memory
Can retrieve the contents of a cell without losing the
contents
(a)
(b)
210
Me m o ry
ce ll
1002
Programming and Problem Solving with Java
210
210
Me m o ry
ce ll
1002
17
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
Programming and Problem Solving with Java
Files are stored in
rings called tracks
Read/w rite
head
Magnetic
recording
surface
18
Programming a Computer
How we solve most problems without a computer
Analyze the problem, come up with a solution
Problem
Statement
Problem
Solution
Programming and Problem Solving with Java
19
Programming a Computer
How we can get the
computer to solve a
problem
Problem
Statement
 Must come up with
an algorithm (series
of steps)
 Computer follows
the steps to solve
the problem
Algorithm
to solve
Problem
(Program)
Problem
Solution
Programming and Problem Solving with Java
20
Programming a Computer
Algorithm
Steps that a computer can follow to solve a problem
Holiday Cookies
1 cup sugar
3/4 cup shortening
1 cup dark corn syrup
2 eggs
1 lemon rind (grated)
3 cups flour
1 tsp. baking powder
1 tsp. baking soda
1/4 tsp. ginger
Similar to
1 tsp. cinnamon
1/2 tsp. nutmeg
a recipe
1/2 tsp. cloves
2 tsp. anise seed
3/4 tsp. ground cardaman
icing (powder sugar and water)
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.
Programming and Problem Solving with Java
21
Programming a Computer
Recipe lists steps, but doesn’t say who is doing the
steps
Implied that you (the cook) should do the steps
Many algorithms written this way -- structured approach
to programming
New 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 step
Similar to the script for a play
Programming and Problem Solving with Java
22
Programming a Computer
THE IMPORTANCE OF BEING EARNEST
by Oscar Wilde
The Persons of the Play
John Worthing, J.P.
Algernon Moncrieff
Rev. Canon Chasuble, D.D.
Merriman, Butler
Lane, Manservant
Lady Bracknell
Hon. Gwendolen Fairfax
Cecily Cardew
Miss Prism, Governess
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
23
Programming a Computer
THE IMPORTANCE OF BEING EARNEST (continued)
ACT ONE
SCENE. 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
24
Programming a Computer
THE 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
25
Programming a Computer
Why is an object-oriented algorithm like a script?
Object-oriented algorithm simulates activities of several
explicit actors
Each actor has specific steps to perform
Each actor free to use any appropriate technique to
accomplish its task
Combined effort of all these simulated actors results in
the goal of the algorithm
Combined effort of real actors of a play results in
enjoyable entertainment
Programming and Problem Solving with Java
26
Programming a Computer
Programming 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 languages
Will use Java in this course
Programming and Problem Solving with Java
27
Programming a Computer
Computers understand machine language directly
Example: add 16 and 23 in Intel 8086 machine language
1011 0000 0001 0000
0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
OK ...
1011 0000 0001 0000
0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
Programming and Problem Solving with Java
28
Programming a Computer
Parts of machine language program step
First statement from example
1011 0000 0001 0000
Copy information
to a register
Use the
AL register
The number 16
in binary (base 2)
Instruction says: Copy the number 16 into the AL register
Difficult to read and write machine language!
Programming and Problem Solving with Java
29
Programming a Computer
Assembly language
One step up from machine language
Each 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
30
Programming a Computer
Assembly language
Huh?
Computer can’t understand
assembly language directly
MOV AL,16D
ADD AL,23D
MOV [SUM],AL
Must translate from assembly to
machine language
Assembler: program that does this
translation
MOV AL,16D
ADD AL,23D
MOV [SUM],AL
Programming and Problem Solving with Java
Assembler
Ok ...
1011 0000 0001 0000
0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
31
Programming a Computer
High-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:
1011 0000 0001 0000
sum = 16 + 23;
0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
(Note: Java usually translated to Java bytecodes, not Intel machine language...)
Programming and Problem Solving with Java
32
Programming a Computer
High-level languages
Must translate high-level language program to machine
language before computer can execute it
Compiler: program that does this translation
Ok ...
sum = 16 + 23;
Compiler
Programming and Problem Solving with Java
1011 0000 0001 0000
0000 0100 0001 0111
1010 0010 0100 1000 0000 0000
33
Programming a Computer: Java
The Java Programming Language
A high-level language
Java compiler translates to Java bytecodes for execution
on a Java Virtual Machine (JVM)
sum = 16 + 23;
Java
C o m p iler
JVM
Ma ch in e
L a n gu a g e
Ok ...
Ja va Virtu a l 1011 0000 0001 0000
Ma ch in e
0000 0100 0001 0111
Tra n s la tor 1010 0010 0100 1000 0000 0000
Programming and Problem Solving with Java
34
Programming a Computer: Java
Advantage of Java Virtual Machine approach
Can run compiled Java program on any machine with a
Java Virtual Machine installed
Makes compiled Java programs very portable
Disadvantage
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
35
Programming a Computer: Java
Kinds of Java programs
Applications
Applets
Applications
Run as stand-alone programs
Programs stored on the same machine they run on
Like a text editor, word processor, spreadsheet, ...
Can be graphical or console-based
Applets
Run inside a web browser
Programs stored on a web server, run on a client
machine
Programming and Problem Solving with Java
36
Programming a Computer: Java
Example 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 program
Type the program text exactly
Save the program in file Add16And23.java
Compile the program with a Java compiler
Run program Add16And23.class with a JVM interpreter
Programming and Problem Solving with Java
37
Programming a Computer: Java
Use an editor that saves text files, such as MS-DOS
edit (in MS-DOS box)
Programming and Problem Solving with Java
38
Programming a Computer: Java
Compile the program
javac Add16And23.java
Run the program
java Add16And23
Result: program should display
The sum of 16 and 23 is 39
$ javac Add16And23.java
$ java Add16And23
The sum of 16 and 23 is 39
$
Unix display
Programming and Problem Solving with Java
39
Programming: Development
Example program: display average of series
First step: understand the problem
Where should program get the numbers? Keyboard
How does program know how many numbers? Will enter
0 at end of list
Where should program display result? On screen
Second step: come up with algorithm
Solve problem yourself -- write down steps you took
Result is an algorithm
Programming and Problem Solving with Java
40
Programming: Development
Steps for
finding average
of series of
numbers
Programming and Problem Solving with Java
Step
Number
Action
Value of
input
data
Value of
running
total
Value of
running
count
Value of
average
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 the
running total by the count
0
20.2
3
6.73
19
Display the average
0
20.2
3
6.73
41
Programming: Development
Convert steps into an algorithm
Display the program's title
Set 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
42
Programming: Development
Convert
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
43
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
44
Programming: Development
Last step: Make sure the program works correctly
First test -- ok
--- Compute Average --Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
The average is 6.73333
9
3.2
8
0
--- Compute Average --Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
The average is 5.79429
9.1
2.6
7.3
1.4
6.44
8
5.72
0
Second test -- ok
Third test -- not ok (doesn’t work if nothing to average)
--- Compute Average --Enter a value (0 to stop): 0
The average is NaN
Programming and Problem Solving with Java
45
Programming: Development
Modified
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
46
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;
}
if (runningCount > 0)
{
// Compute the average
average = runningTotal / runningCount;
Changes
}
// Read the next input value
System.out.print("Enter a value (0 to stop): ");
System.out.flush();
inputValue
= formatter.parse(inStream.readLine()).doubleValue();
// Display the average
System.out.println("The average is " + average);
}
}
else
System.out.println("Can't compute average: No input values");
Programming and Problem Solving with Java
47
Programming: Development
Last step: Test program again
First test -- ok
--- Compute Average --Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
The average is 6.73333
9
3.2
8
0
--- Compute Average --Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
Enter a value (0 to stop):
The average is 5.79429
9.1
2.6
7.3
1.4
6.44
8
5.72
0
Second test -- ok
Third test -- ok
--- Compute Average --Enter a value (0 to stop): 0
Can't compute average: No input values
Programming and Problem Solving with Java
48
Programming: Development
Steps in program development
Understand the problem
Come up with an algorithm
Write the program
Test the program
Programming and Problem Solving with Java
49
Programming: Development
Understand 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 problem
Look at input and output requirements
Ask people involved with the problem domain
Try writing about the program -- write what it should do in
your own words
Programming and Problem Solving with Java
50
Programming: Development
Come up with an algorithm
Algorithm 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 to
will terminate -- won’t go on forever
Programming and Problem Solving with Java
51
Programming: Development
Write the program
If you have an algorithm this step is mechanical
Gets easier the more you learn and use Java
Desk checking
Simulate the action of the
computer in your mind
Good time to do this is as
you write the program
(you’re thinking about
the program anyway)
Programming and Problem Solving with Java
52
Programming: Development
Test the program
Try the program with sample data
Make 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
53
Types of Computers
Four major types of computer systems
Single-user personal computer
Time-sharing computer
Batch computer
Network computer system
Programming and Problem Solving with Java
54
Types of Computers
Single-user personal computer
One person uses at a time
Has become popular since early 80’s
Interactive -- computer responds
immediately to user commands
Programming and Problem Solving with Java
55
Types of Computers
Time-sharing computer
Many people can use simultaneously
Each person uses a terminal
connected to the computer
Printer
Minicomputer
Programming and Problem Solving with Java
56
Types of Computers
How does time-sharing computer service many
people simultaneously?
Only appears to act this way
Actually does a little bit of work for each person in turn
Process is called polling
Polls so fast that it seems like the computer is serving
everyone at the same time
Programming and Problem Solving with Java
57
Types of Computers
Batch 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: efficiency
Used in large companies for repetitive tasks
Payroll, accounting, ...
Printer
Programming and Problem Solving with Java
Mainframe
58
Types of Computers
Computer network
Group of connected computers
Server: fast, expensive computer that stores programs
and other files for the other computers (clients)
Advantage of network vs. time-sharing
Each client is a computer
Response time is better
Desktop computer
Desktop computer
Printer
Disk Array
Server
Programming and Problem Solving with Java
59
Desktop computer
Desktop computer
History of Computers
Abacus: oldest mechanical calculating aid
Invented in Babylon about 3000 years ago
Also used by Chinese
Each 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
60
History of Computers
Blaise Pascal
Invented first mechanical calculator in 1642
Did multiplication and division
Gottfried von Leibnitz
Expanded Pascal's machine in 1671
Handled multiplication, division, and square roots
Joseph-Marie Jacquard
Invented loom that read tape of punched cards in 1801
Wove cloth according to instructions on cards
First machine that could be reprogrammed
Programming and Problem Solving with Java
61
History of Computers
Charles Babbage
Designed Difference Engine (mid 1800’s)
Supposed to compute and print mathematical tables
Never completed -- Babbage spent time designing
Analytical Engine
Designed to follow instructions in a program and thus
handle any computation
Would store program on cards in the machine's memory - this is the stored program concept
Never completed -- English government stopped the
funding
Probably wouldn’t have worked -- required metalworking
skills beyond what was possible at the time
Programming and Problem Solving with Java
62
History of Computers
Augusta Ada (later Countess of Lovelace)
World’s first computer programmer
Assisted Babbage
Translated 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
63
History of Computers
Herman 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
64
History of Computers
Howard Aiken
Designed the Mark I computer -- the world's first
automatic computer (1944)
Operated with electro-mechanical switches
Able to multiply two numbers together in six seconds
John W. Mauchly and J. Presper Eckert
Designed ENIAC -- the first general-purpose electronic
computer (1946)
Hundreds of times faster than any electro-mechanical
computing device
Programmed by plugging wires into holes along the
outside of the machine.
Programming and Problem Solving with Java
65
History of Computers
First generation computers (1950’s)
UNIVAC I (1951, Sperry-Rand): first commercial
computer
Other companies soon followed
Computers were bulky, unreliable
Used vacuum tubes for electronic switching (hot -burned out often)
Most programs
written in machine
language
Used punched
cards for data storage
12345
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 22 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 33 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 33 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 44 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 44 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 55 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 55 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 66 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 66 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 77 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 77 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 88 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 88 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 99 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 99 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
00000000011111111112222222222333333333344444444445555555555666666666677777777778
12345678901234567890123456789012345678901234567890123456789012345678901234567890
Programming and Problem Solving with Java
66
History of Computers
Second generation computers (late 50’s mid 60’s)
Started using transistors instead of vacuum
tubes
Computers became more reliable
First high-level languages (FORTRAN, COBOL,
Algol)
Larger primary memory
Magnetic tapes used for long-term data storage
Programming and Problem Solving with Java
67
History of Computers
Third 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
68
History of Computers
Fourth 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 reliable
Time-sharing popular in 1970’s and 1980’s
Today, single-user personal computers are popular
The Internet connects many computers in a world-wide
computer network
Programming and Problem Solving with Java
69
Software Crisis
Hardware vs. software
Hardware: physical parts of the computer
Software: computer programs
Advances in hardware have been spectacular
Fast, affordable computer systems
Computers in everyday appliances
Advances in software
Have 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
70
Software Crisis
Today, many programs are
Expensive: they cost much more than initial projections
Unreliable: they have serious errors which cause them
to work incorrectly
Late: they are delivered months or years after they're
promised
This is a crisis ...
Programming and Problem Solving with Java
71
Software Crisis
Abstraction
Ignore details, concentrate on essential features
Most powerful tool to solve the software crisis
Levels of abstraction
Sometimes, details at one level become essential
features at another level
Example: stereo
•Consumer level: concentrate on tuner, CD player, tape desk, speakers,
amplifier
•Stereo designer: concentrate on circuits,
discrete parts, chips
•Chip designer: concentrate on circuits
within the chip
Programming and Problem Solving with Java
72
Software Crisis
Use abstraction when writing computer program
Programmer gives a name to each part of the program
When working within the part, programmer concentrates
on the steps within that part
When working outside the part, programmer thinks of the
part by its name (ignores the steps within)
Usually several levels of abstraction in a computer
program
Method: most detailed level
Class: consists of several methods (and other things...)
Package: consists of several classes
System of packages: consists of several packages
Programming and Problem Solving with Java
73
Programming Languages
Hundreds of high-level programming languages
No best programming language for all uses
Some are better than others for certain uses
Four major groups
Procedural
Functional
Logic
Object-oriented
Programming and Problem Solving with Java
74
Languages: Procedural
Procedural languages
Largest group of languages
Also called imperative languages
Program consists of list of statements
Variables
Program stores temporary values in variables, and can
change the value of a variable
Different 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
75
Languages: Procedural
BASIC (Beginner’s All-purpose Symbolic Instruction
Code)
Popular language for beginners
Simple syntax (originally only 14 statement types)
Can run on small computers
Example
10
20
30
40
50
REM THIS BASIC
REM 16 AND 23,
LET SUM = 16 +
PRINT "The sum
END
PROGRAM FINDS THE SUM OF
THEN DISPLAYS THE RESULT.
23
of 16 and 23 is ", SUM
Microsoft Visual BASIC
Much more sophisticated version of BASIC
Full-fledged development system for Microsoft Windows
Programming and Problem Solving with Java
76
Languages: Procedural
COBOL (COmmon Business Oriented Language)
Most commonly used language in business
Designed for ease of data movement
Example
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
77
Languages: Procedural
FORTRAN (FORmula TRANslator)
The first high-level language
Popular with scientists and engineers (although many
engineers are switching to C and C++ today)
Example
C
C
PROGRAM ADDNUMS
THIS FORTRAN PROGRAM FINDS THE SUM OF
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
78
Languages: Procedural
C
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
79
Languages: Procedural
Pascal (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
Example
PROGRAM 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
80
Languages: Functional
Functional languages
Based on mathematical functions
Program consists of functions and function calls
No variables in a pure functional language
Lisp
Most popular functional language
Used 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
81
Languages: Logic
Logic languages
Based on formal rules of logic and inference
Once set, program can't change value of a variable
Program consists of a set of known facts, plus rules for
inferring new facts from the existing facts
Programming and Problem Solving with Java
82
Languages: Logic
Prolog
Most popular logic language
Used 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
83
Languages: Logic
Another 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 query
Example
Goal: likes(jill, Food)
Food=taco
Food=apple
2 Solutions
Can also infer solutions based on known facts
Goal: likes(jody, Food)
Food=apple
1 Solution
Programming and Problem Solving with Java
84
Languages: Object-oriented
Object-oriented languages
Model each real-world entity as an object
Each object has set of values and behaviors
Each object is therefore active, because it has behaviors
Simula (Simulation language)
First object-oriented language (1967)
Smalltalk
First pure object-oriented language (early 1980’s)
Everything in the language is an object
Programming and Problem Solving with Java
85
Languages: Object-oriented
C++
Introduced in the mid 1980’s
Based on the C language
Hybrid language: procedural & object-oriented
Example:
// 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
86
Languages: Object-oriented
Java
Introduced in 1995 by Sun Microsystems
Object-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 appliances
Released version designed for use on the Internet and as
a general-purpose programming language
Probably the most famous programming language of all
time
•Lots of coverage in regular news, unlike other programming languages
•Huge excitement about the language
Programming and Problem Solving with Java
87