Chapter 6: Low-Level Programming Languages
Chapter 6Low-Level
Programming Languages
Page 51
In order to execute instructions on a CPU, those instructions must be in the particular binary format that was designed for that CPU.The set of instructions available for a particular CPU is known as its machine language.
Sample Machine Instruction Format
Op-Code Field
(specifies the operation to be
performed)
Operand Field
(gives further details pertinent to the operation)
Simplified Machine Language
Chapter 6Low-Level
Programming Languages
Page 52
Op-Code Operand Description1 RXY LOAD register R with the bit pattern found at main memory address XY2 RXY LOAD register R with the bit pattern XY3 RXY STORE the bit pattern in register R at main memory address XY4 0RS MOVE the bit pattern in register R to register S
5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R
6 RST ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R
7 RST OR the bit patterns in registers S and T and put the result in register R8 RST AND the bit patterns in registers S and T and put the result in register R9 RST XOR the bit patterns in registers S and T and put the result in register RA R0X ROTATE the bit pattern in register R a total of X bits to the right
B RXYJUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence
C 000 HALT execution
Note that every instruction is sixteen bits (four hexadecimal digits) in length.
Sample Program
Chapter 6Low-Level
Programming Languages
Page 53
205C Load register 0 with the integer 92 (hexadecimal 5C)300E Store the contents of register 0 at main memory
address 0E205A Load register 0 with the integer 90 (hexadecimal 5A)300F Store the contents of register 0 at main memory
address 0F110E Load register 1 with the bit pattern at main memory address 0E120F Load register 2 with the bit pattern at main memory address 0F5012 Add the contents of registers 1 & 2 and put the sum in register 0300D Store the contents of register 0 at memory address 0DC000 Halt execution
In an advanced language, like C++, this program would be:void main()
{ int X, Y, Z; X = 92; Y = 90; Z = X + Y;}
Op-Code Operand Description
1 RXY LOAD register R with the bit pattern found at main memory address XY
2 RXY LOAD register R with the bit pattern XY
3 RXY STORE the bit pattern in register R at main memory address XY
4 0RS MOVE the bit pattern in register R to register S
5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R
6 RST ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R
7 RST OR the bit patterns in registers S and T and put the result in register R
8 RST AND the bit patterns in registers S and T and put the result in register R
9 RST XOR the bit patterns in registers S and T and put the result in register R
A R0X ROTATE the bit pattern in register R a total of X bits to the right
B RXY JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence
C 000 HALT execution
Another Sample Program
Chapter 6Low-Level
Programming Languages
Page 54
Op-Code Operand Description1 RXY LOAD register R with the bit pattern found at main memory address XY
2 RXY LOAD register R with the bit pattern XY
3 RXY STORE the bit pattern in register R at main memory address XY
4 0RS MOVE the bit pattern in register R to register S
5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R
6 RST ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R
7 RST OR the bit patterns in registers S and T and put the result in register R
8 RST AND the bit patterns in registers S and T and put the result in register R
9 RST XOR the bit patterns in registers S and T and put the result in register R
A R0X ROTATE the bit pattern in register R a total of X bits to the right
B RXY JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence
C 000 HALT execution
How would we code this pseudocode with our machine language?
Procedure negative (x) If x < 0 Then return 1 Else return 0
We’ll assume that the value of x has already been stored in main memory at address 5A, that the returned value (0 or 1) will be placed at address 5B, and that the program itself will be stored starting at address D0.
Chapter 6Low-Level
Programming Languages
Page 55
Op-Code Operand Description1 RXY LOAD register R with the bit pattern found at main memory address XY
2 RXY LOAD register R with the bit pattern XY
3 RXY STORE the bit pattern in register R at main memory address XY
4 0RS MOVE the bit pattern in register R to register S
5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R
6 RST ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R
7 RST OR the bit patterns in registers S and T and put the result in register R
8 RST AND the bit patterns in registers S and T and put the result in register R
9 RST XOR the bit patterns in registers S and T and put the result in register R
A R0X ROTATE the bit pattern in register R a total of X bits to the right
B RXY JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence
C 000 HALT execution
Procedure negative (x) If x < 0 Then return 1 Else return 0
Let’s take
advantage of the fact that if an 8-
bit two’s-complem
ent number
is ANDed with
10000000, the
result is 00000000 if the number
is positive,
and 10000000 if the number
is negative.
Address
Contents Meaning of Instruction
D0D1
115A
LOAD register 1 with the value of x (stored at address 5A)
D2D3
2080
LOAD register 0 with the eight bit sequence 10000000
D4D5
8201
AND the contents of registers 0 and 1, putting the result in register 2
D6D7
B2DC
If the result is 10000000 (i.e., if x is negative), jump to the instruction at RAM address DC
D8D9
2300
Otherwise, load register 3 with the number 0
DADB
B0DE
Jump to the instruction at main memory location DE
DCDD
2301
Load register 3 with the number 1
DEDF
335B
Store the contents of register 3 in main memory at address 5B
E0E1
C000
Halt execution
Chapter 6Low-Level
Programming Languages
Page 56
To make programming easier to handle, special languages (unique to the kinds of computers running them) have been developed.
Machine Language Feature
Corresponding Assembly Language Feature
Hexadecimal Op-CodesMnemonic Operators (“LOADVAR”, “JUMPEQ”,
etc.)Data In Specific Main Memory
LocationsUser-Defined Variable Names (“X”, “RESULT”)
Instruction Addresses In Main Memory
User-Defined Instruction Labels (“NEGATIVE”, “STOREIT”)
Programs written in such an assembly language are executed by first passing through a special program (called an assembler) that translates the assembly language code into machine language.
Assembly Language
Example: LOADVAR R1,X LOADHEX R0,80 AND R2,R0,R1 JUMPEQ R0,R2,NEGATIVE LOADHEX R3,00 JUMPEQ R0,R0,STOREITNEGATIVE LOADHEX R3,01STOREIT STORE R3, RESULT HALT
Chapter 6Low-Level
Programming Languages
Page 57
While assembly languages are easier to use than machine languages, they still share two big problems with machine languages.
Assembly Language Problems
1. Assembly languages are still machine-dependent.
A program written in one machine’s assembly
language cannot be executed on a computerwith a different instruction set and register
configuration.
2. Assembly language programming is still too nitpicky.
Programmers are forced to concentrate on thetiny details necessary to choreograph the
computer’s activity, instead of focusing on the overall solution of the problem being tackled.
Chapter 7: Problem Solving andAlgorithm Design
Chapter 7Problem
Solving and Algorithm
DesignPage 58
In general, how are problems solved on a computer?
Analysis & Specification
Understand the
problem
Specify what the program needs to
do
Algorithm Development
Formulate sequence of steps
for solving problem
Test that the steps work for certain
key cases
Implementation
Translate the
algorithm into a
programming language
Test whether the program
produces correct results
Maintenance
Deliver the program and have real users
use it
Debug and upgrade
the program
as needed
Algorithms
Chapter 7Problem
Solving and Algorithm
DesignPage 59
An algorithm is an ordered set of unambiguous, executable steps that ultimately terminate if followed.
Ambiguous:
Not executable:
No termination
:
• Lather•Rinse•Repeat
Computer Algorithms
Chapter 7Problem
Solving and Algorithm
DesignPage 60
In computer programming, an algorithm is the sequence of steps (i.e., the “recipe”) for accomplishing a task.Every step in an algorithm has two basic
components:1. Semantics: The meaning of the step2. Syntax: The format of the step
Semantics
Get a value from the user
Double that value
Return the result to the user
Pseudocode
Chapter 7Problem
Solving and Algorithm
DesignPage 61
Pseudocode is an informal notation for expressing an algorithm.Procedure Sat1231A
Set year to 2001 Set month to January Set day to first Saturday in January 2001 While (year < 2021) Do { Increment day by 7 If date is New Year’s Eve Then display year as having a Saturday New Year’s Eve If day > (number of days in month) Then { Adjust day by subtracting the number of days in month If month is December Then { Increment year by 1 Set month to January } Else Increment month by one } }
Example: Which years in
2001-2020 have New
Year’s Eve on Saturday?
Algorithm Alternatives
Chapter 7Problem
Solving and Algorithm
DesignPage 62
It’s possible to devise many algorithms to solve the same problem.
Procedure Sat1231B Set day_of_week to 12/31/2000 Set year to 2001 While (year < 2021) Do { If year is a leap year Then increment day_of_week by 2 Else increment day_of_week by 1 If day_of_week is Saturday Then display year as having a Saturday New Year’s Eve Increment year by 1 }
Alternative pseudocode to
determine which years in 2001-2020 have New Year’s Eve on
Saturday.
Both algorithms work, but which is better?
Which is easier to code?
Which runs more efficiently?
Program Modularity
Chapter 7Problem
Solving and Algorithm
DesignPage 63
The software development process usually involves a team of developers, so the software is often designed as a hierarchical system of modules, which can be viewed as easily modified interdependent entities.
Advantages of Modular Programming
Chapter 7Problem
Solving and Algorithm
DesignPage 64
Modifiability
It’s easier to alter or
upgrade the program if
changes can be
segregated to particular
modules
Debuggability
It’s easier to diagnose
and pinpoint problems with the
program if it’s split into
logically distinct modules
Reusability
Generic modules can
be developed and then reused in
other programs, eliminating the need to “reinvent
the wheel”
Readability
It’s easier to read
someone else’s
program or refresh you
memory about your
own program if it’s broken into self-contained
units
Top-Down Design
Chapter 7Problem
Solving and Algorithm
DesignPage 65
One common approach for designing programs is the top-down methodology.1.Design a high-
level solution to the programming problem.
This approach lends itself to modularity.
Process Payroll
Get Input DataRetrieve Timecard Data
Retrieve
Salary Infor
mation
Retrieve Dependent Records
Retrieve
Retirement Plans
Retrieve Tax
Rates
Perform Calculations
Compute Gross Pay
Compute Deductions
Produce Output
Generate Paychecks
Update YTD Records
2.Consider each complicated subproblem as a separate programming problem.
3.Return to step #1 with each subproblem.
However, it may impose an artificial hierarchy on the tasks being performed.
Bottom-Up Design
Chapter 7Problem
Solving and Algorithm
DesignPage 66
A newer approach for designing programs is the bottom-up methodology.1.Separate each major
task in the overall problem into an individual programming problem.
This approach produces reusable modules.
Video Game Engine
Physics Engine
Fluid Dynamics
Engine
Particle
Systems
Engine
Collision
Detection
Engine
Math Engine
Rotational Calculation
EngineFractal Engine
Artificial Intelligence Engine
Intelligent Agent Engine
Behavior Prediction
Engine
2.Develop cooperative programming solutions to the separate problems.
However, those modules may prove difficult to cobble together to solve bigger problems.
Chapter 8: Abstract Data Types and Algorithms
Chapter 8Abstract
Data Types and
AlgorithmsPage 67
Two keys to making computer software that works well:• Organize data so it can be accessed and
processed efficiently.• Develop algorithms that take advantage of the strengths of the programming language and the hardware to accomplish what the program is attempting to do.
Iteration
Chapter 8Abstract
Data Types and
AlgorithmsPage 68
Pseudocode to implement the search for a specific name in an alphabetized phonebook:
Procedure SeqSearch(phonebook, sought_name) Set test_name to first name in phonebook While (test_name is alphabetically before sought_name AND there are still more names in phonebook) Do Set test_name to the next name in phonebook If test_name is sought_name Then return the corresponding phone number Else return “Unlisted” message
When an algorithm involves repetitive actions, iteration (i.e., looping) may be a practical approach.
Notice that this algorithm always starts at the top of the phonebook list and checks each name against sought_name until it either locates it or (if it’s not in the phonebook) passes it.
Chapter 8Abstract
Data Types and
AlgorithmsPage 69
Calling SeqSearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and
phonebook is the list below:Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
test_name is Sirius Black, so iterate again
test_name is Cho Chang, so iterate again
test_name is Albus Dumbledore, so iterate againtest_name is Dudley Dursley, so iterate again
test_name is Argus Filch, so iterate again
test_name is Cornelius Fudge, so iterate againtest_name is Hermione Granger, so iterate againtest_name is Rubeus Hagrid, so return 555-1317
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Chapter 8Abstract
Data Types and
AlgorithmsPage 70
Recursion
Pseudocode to recursively take a base number to a specified power:
Procedure Exponentiate(base, power) If base is 0 Then return 0 Else If power < 0 Then return Exponentiate(base, power+1)/base Else If power is 0 Then return 1 Else return base * Exponentiate(base, power-1)
Another common approach in algorithms is to employ recursion (i.e., “divide and conquer”), which repeatedly reduces the size of a problem until it becomes manageable.
Notice that this algorithm returns 0 if the value of base is 0, 1 if the value of power is 0, base if the value of power is 1, 1/base if the value of power is -1, and so on.
Chapter 8Abstract
Data Types and
AlgorithmsPage 71
A Recursive Search AlgorithmPseudocode to recursively implement the search for a specific name in an alphabetized phonebook:Procedure BinarySearch(phonebook, sought_name) Set test_name to the middle name in phonebook If test_name is sought_name Then return corresponding phone number Else If phonebook has only one remaining entry Then return “Unlisted” message If test_name is alphabetically before sought_name Then apply BinarySearch to the portion of phonebook after test_name Else apply BinarySearch to the portion of phonebook before test_nameNotice that this algorithm starts at the middle of the phonebook list, and keeps splitting what’s left of the phonebook in half until it either locates sought_name or runs out of names to check.
Chapter 9Abstract
Data Types and
AlgorithmsPage 22
Chapter 8Abstract
Data Types and
AlgorithmsPage 72
Calling BinarySearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and
phonebook is the list below:Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
test_name is Gilderoy Lockhart, so iterate again
test_name is Rubeus Hagrid, so return 555-1317
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
test_name is Dudley Dursley, so iterate again
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
test_name is Cornelius Fudge, so iterate again
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
test_name is Hermione Granger, so iterate again
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Name NumberBlack, Sirius
Chang, ChoDumbledore, AlbusDursley, DudleyFilch, ArgusFudge, CorneliusGranger, HermioneHagrid, RubeusLockhart, GilderoyLongbottom, NevilleMalfoy, DracoMcGonagall, MinervaPettigrew, PeterPomfrey, PoppySnape, SeverusTrelawney, SybillWeasley, RonWood, Oliver
555-7458555-0131555-3589555-1119555-3783555-9927555-2728555-1317555-1201555-7936555-7174555-1659555-2941555-1503555-8847555-6296555-5165555-6793
Address
Contents
00
01
:
Memory cell 71 (hex 47) >
47 78
48 87
49 74
: :
A9 80
Memory cell 170 (hex AA) >
AA 85
:
FE
FF
Chapter 8Abstract
Data Types and
AlgorithmsPage 73
Data StructuresWhen interrelated information is stored in a computer’s memory, it is usually convenient for the programmer (and for the computer’s memory management) to keep this data in a structured format.
Example:int IQlist[100];
Conceptually, the array looks something like this:
Index 0 1 2 … 98 99
Contents
120 135 116 … 128 133
However, in the computer’s RAM, space for 100 integers has been allocated something like this:
An array is an indexed list of values of the same type.
Chapter 8Abstract
Data Types and
AlgorithmsPage 74
Example:int GradeTable[3][5];
Conceptually, the array looks something like this:
COLUMN #
0 1 2 3 4
ROW #
0 94 89100
87 92
1 68 90 84 78 86
2 77 95 97 100 88
However, in the computer’s RAM, space for 15 integers has been allocated something like this:
Address
Contents
00
01
:
Space for element (0,0) >
B2 5E
(0,1) > B3 59
(0,2) > B4 64
(0,3) > B5 57
(0,4) > B6 5C
(1,0) > B7 44
(1,1) > B8 5A
(1,2) > B9 54
(1,3) > BA 4E
(1,4) > BB 56
(2,0) > BC 4D
(2,1) > BD 5F
(2,2) > BE 61
(2,3) > BF 64
(2,4) > C0 58
:
FF
A multidimensional array is an indexed table of values of the same type, using more than one dimension.
Chapter 8Abstract
Data Types and
AlgorithmsPage 75
Rather than reserving a contiguous block of memory to store a list, the linked list dynamically allocates memory as needed for list elements.
Example:struct node;typedef node *nodePtr;struct node{ int value; nodePtr next;};
nodePtr List;
Conceptually, the linked list looks something like this:
97 100 88 94
However, in the computer’s RAM, space for 4 integers has been allocated something like this:
Address
Contents
00
:
16 64
3rd item is at address B0
17 B0
:
4E 5E
FF signifies the end of List
4F FF
:
List is located at 9A 9A 61
2nd item is at address 16
9B 16
:
B0 58
4th item is at address 4E
B1 4E
:
FF
Chapter 8Abstract
Data Types and
AlgorithmsPage 76
Relative Advantages of Arrays & Linked ListsArrays Linked Lists
Require contiguous memory
Dynamically locate memoryRequires specific size Has flexible size
Potentially wastes memory
Only uses allocated spacePotentially runs out of
memoryExpands memory as neededInsertion requires
rearrangingInsertion requires slight relinkDeletion requires
rearrangingDeletion requires slight relinkOne-by-one searching required
Indexing facilitates searching Sequential search onlyBinary search possible if sorted Tougher to
conceptualizeStraightforward to program Complicated garbage
collectionMemory easily cleared after use
Chapter 8Abstract
Data Types and
AlgorithmsPage 77
Comparison: Retrieving a List from a FileUsing an array Using a linked list
void GetList(int List[50], int &ListSize){ ifstream file; char fileName[50]; int val;
cout << "Enter the name " << "of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail());
ListSize = 0; file >> val; while ((!file.eof()) && (ListSize < 50)) { List[ListSize] = val; ListSize++; file >> val; } file.close();}
void GetList(nodePtr &List){ ifstream file; char fileName[50]; int val; nodePtr ptr;
cout << "Enter the name " << “of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail());
List = NULL; file >> val; while (!file.eof()) { ptr = new node; ptr->value = val; ptr->next = List; List = ptr; file >> val; } file.close();}
Extra concern: Exceeding array’s size Extra concern: Allocating new
memory
void GetList(int List[50], int &ListSize){ ifstream file; char fileName[50]; int val;
cout << "Enter the name " << "of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail());
ListSize = 0; file >> val; while ((!file.eof()) && (ListSize < 50)) { List[ListSize] = val; ListSize++; file >> val; } file.close();}
void GetList(nodePtr &List){ ifstream file; char fileName[50]; int val; nodePtr ptr;
cout << "Enter the name " << “of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail());
List = NULL; file >> val; while (!file.eof()) { ptr = new node; ptr->value = val; ptr->next = List; List = ptr; file >> val; } file.close();}
Chapter 8Abstract
Data Types and
AlgorithmsPage 78
Comparison: Sequential SearchUsing an array Using a linked list
int Search(int List[50], int ListSize, int soughtVal){ int count; bool found = false;
count = 0; while ((!found) && (count < 50)) { if (List[count] == soughtVal) found = true; else count++; } if (found) return List[count]; else return -1;}
int Search(nodePtr List, int soughtVal){ nodePtr currPtr; bool found = false;
currPtr = List; while ((!found) && (currPtr != NULL)) { if (currPtr->value == soughtVal) found = true; else currPtr = currPtr->next; } if (found) return currPtr->value; else return -1}
Note again that the code is almost identical, but the array version is limited to lists of a certain size. If the
list is too long, the array can’t hold it all; if it’s too short, several memory slots are wasted.
Chapter 8Abstract
Data Types and
AlgorithmsPage 79
Sorting Algorithms
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Somewhat more complicated than searching an alphabetized list is the problem of alphabetizing such a list to begin with.
Numerous sorting algorithms have been developed, each with its own advantages and disadvantages with respect to:
• Speed with which it sorts a completely random list• Speed with which it sorts a nearly sorted list• Amount of memory required to implement it• Ease with which it can be coded
Examination of three such algorithms follows, with each algorithm applied to the following list of 26 three-letter names:
Chapter 8Abstract
Data Types and
AlgorithmsPage 80
Selection Sort1. Let k equal the size of your list2. Let i equal the index of the first element of your list3. Swap the smallest element in the last k elements with the ith element4. Decrease k by one5. Increase i by one6. If k is still larger than one, repeat, starting at step #3
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaMoe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Ann Edy Zeb Ort Bob Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaAnn Edy Zeb Ort Bob Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Ann Bob Zeb Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaAnn Bob Zeb Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Ann Bob Cub Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Dan Lex Pez Hal TiaAnn Bob Cub Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Dan Lex Pez Hal Tia
Ann Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal TiaAnn Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia
Ann Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal TiaAnn Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia
Ann Bob Cub Dan Edy Fly Moe Uma Quo Kit Wes Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia
Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb
Verdict: Easy to program, little memory waste, very inefficient
Edy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Chapter 8Abstract
Data Types and
AlgorithmsPage 81
Bubble Sort1. Let k equal the size of your list2. Let i equal the index of the first element of your list3. Starting with the ith element of the list and moving down to the kth element, swap
every consecutive pair of elements that is in the wrong order4. Decrease k by one5. Increase i by one6. If k is still larger than one, repeat, starting at step #3
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Verdict: Tougher to program, little memory waste, inefficient in general (but could easily be modified to terminate early if a swap-less pass occurs)
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Edy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaEdy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Edy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Edy Moe Ort Zeb Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Edy Moe Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Zeb
Edy Moe Bob Ort Ann Uma Quo Kit Fly Vin Wes Gus Joe Nan Sue Cub Ida Xon Ren Dan Lex Pez Hal Tia Yul Zeb
Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb
Chapter 8Abstract
Data Types and
AlgorithmsPage 82
Quick Sort1. Let leftIndex be the index of the leftmost element of an unsorted portion of the list and
rightIndex be the index of the rightmost element of that portion of the list2. Let pivot equal the value currently at index p of the list3. Moving in from the rightIndex element of the list, keep moving until a value less than
pivot is found; set rightIndex to the index of that value and insert it at position leftIndex4. Moving in from the leftIndex element of the list, keep moving until a value greater than
pivot is found; set leftIndex to the index of that value and insert it at position rightIndex5. If leftIndex doesn’t equal rightIndex, return to step #3; otherwise, insert pivot at index
leftIndex and return to step #1, starting over with another unsorted portion of the list
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaMoe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia
Moepivot:
Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaHal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaHal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal TiaHal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb TiaHal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb TiaHal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb TiaHal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb TiaHal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb TiaHal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb TiaHal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb TiaHal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb TiaHal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaHal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia
Halpivot:
Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaGus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia
Xonpivot:
Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb TiaGus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Tia Vin Nan Sue Quo Uma Pez Ren Wes Ort Xon Zeb Yul
Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb
Verdict: Much tougher to program, little memory waste, efficient in general (but very inefficient if the list is already almost sorted)
Chapter 8Abstract
Data Types and
AlgorithmsPage 83
Example:
A stack is a data structure that manages a list of similar items in such a way that all insertions and deletions take place at one designated end of the list.In effect, one end of the list is considered the “top” of the
stack, inserting into the list is considered “pushing” an item onto the top of the stack, and deleting from the list is considered “popping” off the top of the stack.
Initial Stack
3After “Push
3”
53
After “Push
5”
853
After “Push
8”
53
After “Pop”
3After “Pop”
13
After “Push
1”
Chapter 8Abstract
Data Types and
AlgorithmsPage 84
Comparison: Stack ImplementationsUsing an array Using a linked list
void Push(int List[50], int &Top, int item){ if (Top < 49) { Top++; List[Top] = item; }}
int Pop(int List[50], int &Top){ int val = -1; if (Top >= 0) { val = List[Top]; Top--; } return val;}
void Push(nodePtr &List, int item){ nodePtr ptr = new node; ptr->value = item; ptr->next = List; List = ptr;}
int Pop(nodePtr &List){ int val = -1; if (nodePtr != NULL) { val = nodePtr->value; List = List->next; } return val;}
Chapter 8Abstract
Data Types and
AlgorithmsPage 85
Example Stack Application
Main: line #3x:0 y:-2 z:?
When Main reaches the
A(); step
A: line #4i:10 j:46 k:31
Main: line #3x:0 y:-2 z:?
When A reaches the
B(); step
B: line #3r:400 s:542 t:?
A: line #4i:10 j:46 k:31
Main: line #3x:0 y:-2 z:?
When B reaches the
C(); step
When C finishes, the stack is popped and B resumes.When B finishes, the stack is popped and A resumes.When A finishes, the stack is popped and Main resumes and finishes.
Keeping track of function calls in a third-generation programming language.
Main Programx = 0;
y = -2;A();z = 6;cout << x << y << z << endl;
Subprogram A()i = 10;
j = 46;k = 31;B();j = 50;cout << i << j << k << endl;
Subprogram B()r = 400;
s = 542;C();r = 710;s = 365;r = 927;cout << r << s << t << endl;
Subprogram C()u = 15;
v = 57;w = 34;cout << u << v << w << endl;
x = 0;y = -2;A();z = 6;cout << x << y << z << endl;
i = 10;j = 46;k = 31;B();j = 50;cout << i << j << k << endl;
r = 400;s = 542;C();r = 710;s = 365;r = 927;cout << r << s << t << endl;
Chapter 8Abstract
Data Types and
AlgorithmsPage 86
Example:
A queue is a data structure that manages a list of similar items in such a way that all insertions take place at one end of the list, while all deletions take place at the other end.In effect, one end of the list is considered the “rear” of
the queue, where new items enter; and the other end is considered the “front” of the queue, where old items are removed.
Initial Queue:
F/R
After Insert 7:
7
F R
After Insert 4:
7 4
F R
After Insert 2:
7 4 2
F R
After Remove:
4 2
F R
After Insert 5:
4 2 5
Chapter 8Abstract
Data Types and
AlgorithmsPage 87
Comparison: Queue ImplementationsUsing an array Using a linked list
void Insert(int List[50], int &Front, int &Rear, int item){ if (Front != (Rear+1)%50) { Rear = (Rear+1)%50; List[Rear] = item; if (Front == -1) Front = Rear; }}int Remove(int List[50], int &Front, int &Rear){ int val = -1; if (Front > -1) { val = List[Front]; if (Front == Rear) Front = Rear = -1; else Front = (Front+1)%50; } return val;}
void Insert(nodePtr &ListFront, nodePtr &ListRear, int item){ nodePtr ptr = new node; ptr->value = item; ptr->next = NULL; if (ListFront == NULL) ListFront = ptr; else ListRear->next = ptr; ListRear = ptr;}int Remove(nodePtr &ListFront,
nodePtr &ListRear){ int val = -1; if (ListFront != NULL) { val = ListFront->value; ListFront = ListFront->next; } if (ListFront == NULL) ListRear = NULL; return val;}
Chapter 8Abstract
Data Types and
AlgorithmsPage 88
Example Queue ApplicationKeeping track of batch jobs as they arrive to be processed by a computer.
Job A arrives and
starts processing:
CPU processin
g Job A
Job Queue:
Job B arrives: CPU
processing Job A
Job Queue:
B
Jobs C & D arrive: CPU
processing Job A
Job Queue:
B C D
Job A completes; Job B starts processing:
Job Queue:
C DCPU processin
g Job B
Chapter 8Abstract
Data Types and
AlgorithmsPage 89
Example Implementation:struct node;typedef node *nodePtr;struct node{ int value; nodePtr left; nodePtr right;};
nodePtr Tree;
A binary tree is a hierarchical data structure that manages a collection of similar items in such a way that one item is designated as the “root” of the tree, and every other item is either the left or right “offspring” of some previously positioned item.8
3 14
1 5
7
10
12
19
16 23
17Example: Binary Insertion Tree
• Each left offspring of a node has a value less than the node’s value
• Each right offspring of a node has a value greater than or equal to the node’s value
Chapter 8Abstract
Data Types and
AlgorithmsPage 90
Recursive Insertion into a Binary Insertion Tree
Example:Where will a new node containing the integer 11 be
inserted?
void Bin_Insert(nodePtr &Tree, int item){ if (Tree == NULL) { nodePtr ptr = new node; ptr->value = item; ptr->left = NULL; ptr->right = NULL; } else if (item < Tree->value) Bin_Insert(Tree->left, item); else Bin_Insert(Tree->right, item);}
8
3 14
1 5
7
10
12
19
16 23
1711
Chapter 8Abstract
Data Types and
AlgorithmsPage 91
Recursive Traversal of a Binary Insertion Tree
Example:Apply Inorder to
this binary insertion tree:
void Inorder(nodePtr Tree){ if (Tree != NULL) { Inorder(Tree->left); cout << Tree->value << endl; Inorder(Tree->right); }}
8
3 14
1 5
7
10
12
19
16 23
17
13578
10121416171923
Chapter 8Abstract
Data Types and
AlgorithmsPage 92
What Does This Function Do To A Binary Tree?int Sumac(nodePtr Tree){ int leftbranch, rightbranch; if (Tree == NULL) return 0; else { leftbranch = Sumac(Tree->left); rightbranch = Sumac(Tree->right); return leftbranch + rightbranch + Tree->value; }}
13
5 20
34 22 7
9 150 0
34
0 0
22
61
0
0 0
9
0 0
15
31
51
125
Chapter 9: High-Level Programming Languages
Chapter 9High-Level
Programming Languages
Page 93
Third-generation languages (e.g., BASIC, FORTRAN, COBOL, C) were developed as a solution to the assembly language problems.Third-generation languages are structured to avoid considering machine operations at all, instead concentrating on relatively straightforward instructions on how the data is being manipulated.Each type of computer that executes programs in a TGL has a special program (called a compiler) that translates the TGL code into the computer’s machine language.Consequently, a TGL program written on one machine can be run on any other computer, as long as the computer has a compiler for that TGL!
Example:
int negative (int x){ if (x < 0) return 1; else return 0;}
Compilation
Chapter 9High-Level
Programming Languages
Page 94
Lexical AnalysisThe compiler takes the TGL program (called the source program) and determines which strings of characters form separate items
(e.g., “if (count > 100)” is split into “if”, “(”, “count”, “>”, “100”, and “)”), and all comments and white space (blanks, line
feeds, etc.) are deleted.
SourceProgram(in TGL)
LexicalAnalysis
ParsingCode
Generation
ObjectProgram
(in MachineLanguage)
ParsingThe compiler then analyzes the grammatical syntax of the
program (e.g., “if”, “(”, “count”, “>”, “100”, “)” is determined to make sense, but a syntax error would be noticed in “if”,
“count”, “>”, “100”, “)”.)Code Generation
Once the program has been satisfactorily parsed, the compiler generates an equivalent program in machine language (called
the object program).
Linking and Loading
Chapter 9High-Level
Programming Languages
Page 95
Since the individual portions of the TGL program are compiled as separate units (e.g., your program, a math library, a graphics library, etc.), the resulting machine code cannot be executed until all of the units are connected together as a single machine language program.
SourceProgram
ObjectProgram
LinkingA TGL programmer usually relies on pre-compiled libraries of code (math functions,
graphics routines, I/O operations, etc.) that are connected to the programmer’s code prior to execution by a linker program.
LoadingFinally, a special loader program places the resulting machine code in main memory, tying
up all loose ends (e.g., setting the instruction addresses for JUMP instructions) so the code is ready for execution.
Compile
Compile
LinkLink LoadModuleLoad
ModuleLoad Executable
ProgramExecutableProgram
Standard Source Program Organization
Chapter 9High-Level
Programming Languages
Page 96
Source programs in most third-generation languages generally follow a standard pattern.void main(){ const int maxCount = 10; int count; int value; float sum = 0.0;
cout << “Input values” << endl; count = 0; while (count < maxCount) { cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl;}
void main(){ const int maxCount = 10; int count; int value; float sum = 0.0;
cout << “Input values” << endl; count = 0; while (count < maxCount) { cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl;}
void main(){ const int maxCount = 10; int count; int value; float sum = 0.0;
cout << “Input values” << endl; count = 0; while (count < maxCount) { cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl;}
Declarative Statements
Constant and variable values
representing terms that will be
manipulated as the program is executed.
Imperative Statements
The procedural specification of the algorithm
itself.
Data Types
Chapter 9High-Level
Programming Languages
Page 97
Data types are used to specify how the bit patterns used to represent data should be interpreted by the program.
int count;float price;bool flag;
Scalar: Single-valued data types (e.g., integer, floating-point, character, boolean)
Structured: Multiple-valued data typesBuilt-In: Arrays, character
strings float CaffeineOuncesPerDay[7];char chosenCola[] = “Pepsi”;
User-Defined: Specially constructedstruct Student
{ char name[30]; int examScore[5]; int quizScore[25]; int paperScore[2]; char letterGrade;};Student FALL111[25];
Imperative Statements - Part One
Chapter 9High-Level
Programming Languages
Page 98
Assignment statements are used to assign a value to a variable.
x = 127;
Input/output statements are used to retrieve external values (input) and to file away or print information (output).
cout << “Enter user’s name: ”;
Assignment
& I/O
c count E m x
186000 78 3309875 5 290
c count E m x
186000 78 3309875 5 127
c count E m x
186000 79 3309875 5 127
c count E m x
186000 79 930000 5 127
c count E m x
186000 79 930000 5 127count = count + 1;E = m * c * c;
Enter user’s name: MOE
25 63 1748 50 7713 91 2389 34 56
nextDataValue
94
25 63 1748 50 7713 91 2389 34 56
25nextDataValue
25
nextDataValue
25
dataFile positiveFile
cin >> username;dataFile >> nextDataValue;if (nextDataValue > 0) positiveFile << nextDataValue;
Imperative Statements - Part Two
Chapter 9High-Level
Programming Languages
Page 99
Conditional statements are used to enable alternative steps based on a condition.if (total == 0) cout << “Possible Drop”;else cout << “Total: ” << total;
Iterative statements are used to loop through a sequence of instructions.
while (flag == false){ cin >> newValue; if (newValue > 0) flag = true;}
switch (AreaCode){ case 701: cout << “ND”; break; case 218: case 507: case 612: cout << “MN”; break;}
total = 0;for (i = 0; i <= 24; i++){ quizFile >> score[i]; total += score[i];}
Control
Statements
Imperative Statements - Part Three
Chapter 9High-Level
Programming Languages
Page 100
Procedures
& FunctionsProcedures and functions are used to conveniently write programs in a modular fashion.
void main(){ intList IQlist; intList SATlist; int maxIQ; int bestSAT;
getList(IQlist); maxIQ = maximum(IQlist); getList(SATlist); bestSAT = maximum(SATlist); cout << “The highest IQ is ” << maxIQ << “ and the ” << “best SAT score is ” << bestSAT;}
typedef int intList[100];
void getList(intList list){ int count; for (count = 0; count < 100; count++) cin >> list[count];}
int maximum(intList list){ int maxSoFar; int count; maxSoFar = list[0]; for (count = 1; count < 100; count++) if (list[count] > maxSoFar) maxSoFar = list[count]; return maxSoFar;}
Example: What Does This Program Do?
Chapter 9High-Level
Programming Languages
Page 101
void main(){ intList estimate; int bestGuesser; int price;
cin >> price; getList(estimate); bestGuesser = drew(estimate, price); if (bestGuesser == -1) cout << “NO WINNER”; else { cout << bestGuesser << “ WINS! ”; if (estimate[bestGuesser] == price) cout << “WITH A BONUS!!!”; }}
typedef int intList[4];
void getList(intList list){ int count; for (count = 0; count < 4; count++) cin >> list[count];}
int drew(intList list, int item){ int bestSoFar, bestIndex, index; bestIndex = -1; bestSoFar = 0; for (index = 0; index < 4; index++) if ((list[index] > bestSoFar) && (list[index] <= item)) { bestIndex = index; bestSoFar = list[index]; } return bestIndex;}
What would be the output of this program for the following input file?
600 400 675 525 450
Object-Oriented Programming
Chapter 9High-Level
Programming Languages
Page 102
Early third-generation programming languages used a “procedure-oriented” approach, in which the way something was done was the center of attention for the programmer.More recently, with the advent of graphical user interfaces and massive databases, the focus has shifted to an “object-oriented” approach, emphasizing what is being manipulated instead of how.
The Three Principles of OOP
Chapter 9High-Level
Programming Languages
Page 103
• “Hide” information from objects that don’t need it.• Is the search being performed sequential or
binary?• Is the data in an array or separate variables?• Is the input coming from the user or from a file?• The code will be more robust if it’s not
unnecessarily dependent on information that it can perform without!
Encapsulation
• Don’t “reinvent the wheel” when creating new data types.• A GUI Window is rectangular with a title bar.• A Document Window also has a menu bar, and
max & min buttons.• Why not let the Document Window “inherit” as
much behavior as possible from the GUI Window (e.g., how to draw it, how to place text in its title bar)?
Inheritance
• Some objects are “similar”, without being the same.• A Triangle object needs its own method for
“Drawing”.• A Circle object needs its own method for
“Drawing”.• With polymorphism, you can write code to invoke
“Drawing” without having to spell out what type of “Drawing” is intended.
Polymorphism