Chapter 6 LowLevel Programming Languages In order to

  • Slides: 53
Download presentation
Chapter 6: Low-Level Programming Languages In order to execute instructions on a CPU, those

Chapter 6: Low-Level Programming Languages 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) Chapter 6 Low-Level Programming Languages Page 51

Simplified Machine Language Op-Code Operand 1 2 3 4 RXY RXY 0 RS 5

Simplified Machine Language Op-Code Operand 1 2 3 4 RXY RXY 0 RS 5 RST 6 RST 7 8 9 A RST RST R 0 X B RXY C 000 Description LOAD register R with the bit pattern found at main memory address XY LOAD register R with the bit pattern XY STORE the bit pattern in register R at main memory address XY MOVE the bit pattern in register R to register S ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R OR the bit patterns in registers S and T and put the result in register R AND the bit patterns in registers S and T and put the result in register R XOR the bit patterns in registers S and T and put the result in register R ROTATE the bit pattern in register R a total of X bits to the right 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 HALT execution Note that every instruction is sixteen bits (four hexadecimal digits) in length. Chapter 6 Low-Level Programming Languages Page 52

Sample Program 205 C 300 E 205 A 300 F 110 E 120 F

Sample Program 205 C 300 E 205 A 300 F 110 E 120 F 5012 300 D C 000 Load register 0 with the integer 92 (hexadecimal 5 C) Store the contents of register 0 at main memory address 0 E Load register 0 with the integer 90 (hexadecimal 5 A) Store the contents of register 0 at main memory address 0 F Load register 1 with the bit pattern at main memory address 0 E Load register 2 with the bit pattern at main memory address 0 F Add the contents of registers 1 & 2 and put the sum in register 0 Store the contents of register 0 at memory address 0 D Halt execution 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 0 RS 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 R 0 X B RXY C 000 ROTATE the bit pattern in register R a total of X bits to the right 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 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; } Chapter 6 Low-Level Programming Languages Page 53

Another Sample Program How would we code this pseudocode with our machine language? Procedure

Another Sample Program How would we code this pseudocode with our machine language? Procedure negative (x) If x < 0 Then return 1 Else return 0 Op-Code Operand We’ll assume that the value of x has already been stored in main memory at address 5 A, that the returned value (0 or 1) will be placed at address 5 B, and that the program itself will be stored starting at address D 0. 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 0 RS 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 R 0 X B RXY C 000 ROTATE the bit pattern in register R a total of X bits to the right 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 HALT execution Chapter 6 Low-Level Programming Languages Page 54

Let’s take advantage Address Contents D 0 11 of the fact D 1 5

Let’s take advantage Address Contents D 0 11 of the fact D 1 5 A that if an 8 D 2 20 bit two’s. D 3 80 complement D 4 82 number is D 5 01 D 6 B 2 ANDed with D 7 DC 10000000, D 8 23 the result is D 9 00 0000 if DA B 0 the number DB DE DC 23 is positive, DD 01 and DE 33 10000000 if DF 5 B the number E 0 C 0 E 1 00 is negative. Meaning of Instruction LOAD register 1 with the value of x (stored at address 5 A) LOAD register 0 with the eight bit sequence 10000000 AND the contents of registers 0 and 1, putting the result in register 2 If the result is 10000000 (i. e. , if x is negative), jump to the instruction at RAM address DC Otherwise, load register 3 with the number 0 Jump to the instruction at main memory location DE Load register 3 with the number 1 Store the contents of register 3 in main memory at address 5 B Halt execution 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 0 RS 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 R 0 X B RXY C 000 ROTATE the bit pattern in register R a total of X bits to the right 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 HALT execution Procedure negative (x) If x < 0 Then return 1 Else return 0 Chapter 6 Low-Level Programming Languages Page 55

Assembly Language To make programming easier to handle, special languages (unique to the kinds

Assembly Language To make programming easier to handle, special languages (unique to the kinds of computers running them) have been developed. 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. Example: LOADVAR R 1, X LOADHEX AND JUMPEQ LOADHEX JUMPEQ NEGATIVE LOADHEX STOREIT STORE HALT R 0, 80 R 2, R 0, R 1 R 0, R 2, NEGATIVE R 3, 00 R 0, STOREIT R 3, 01 R 3, RESULT Machine Language Feature Corresponding Assembly Language Feature Hexadecimal Op-Codes Mnemonic Operators (“LOADVAR”, “JUMPEQ”, etc. ) Data In Specific Main Memory Locations User-Defined Variable Names (“X”, “RESULT”) Instruction Addresses In Main Memory User-Defined Instruction Labels (“NEGATIVE”, “STOREIT”) Chapter 6 Low-Level Programming Languages Page 56

Assembly Language Problems While assembly languages are easier to use than machine languages, they

Assembly Language Problems While assembly languages are easier to use than machine languages, they still share two big problems with machine languages. 1. Assembly languages are still machine-dependent. A program written in one machine’s assembly language cannot be executed on a computer with a different instruction set and register configuration. 2. Assembly language programming is still too nitpicky. Programmers are forced to concentrate on the tiny details necessary to choreograph the computer’s activity, instead of focusing on the overall solution of the problem being tackled. Chapter 6 Low-Level Programming Languages Page 57

Chapter 7: Problem Solving and Algorithm Design In general, how are problems solved on

Chapter 7: Problem Solving and Algorithm Design In general, how are problems solved on a computer? Analysis & Specification Algorithm Development Implementation Maintenance Understand the problem Formulate sequence of steps for solving problem Translate the algorithm into a programming language Deliver the program and have real users use it Specify what the program needs to do Test that the steps work for certain key cases Test whether the program produces correct results Debug and upgrade the program as needed Chapter 7 Problem Solving and Algorithm Design Page 58

Algorithms An algorithm is an ordered set of unambiguous, executable steps that ultimately terminate

Algorithms An algorithm is an ordered set of unambiguous, executable steps that ultimately terminate if followed. Ambiguous: Not executable: No termination: • Lather • Rinse • Repeat Chapter 7 Problem Solving and Algorithm Design Page 59

Computer Algorithms In computer programming, an algorithm is the sequence of steps (i. e.

Computer Algorithms 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 step 2. Syntax: The format of the step Semantics Get a value from the user Syntax Program Double. It; Double that value var x, y integer; Return the result to the user begin write(“Input your number: ”); read(x); y = 2*x; writeln(“The doubled number is ”, y); end. Chapter 7 Problem Solving and Algorithm Design Page 60

Pseudocode is an informal notation for expressing an algorithm. Procedure Sat 1231 A Set

Pseudocode is an informal notation for expressing an algorithm. Procedure Sat 1231 A Set year to 2001 Example: Which Set month to January years in 2001 -2020 Set day to first Saturday in January 2001 have New Year’s Eve While (year < 2021) Do { on Saturday? 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 } } Chapter 7 Problem Solving and Algorithm Design Page 61

Algorithm Alternatives It’s possible to devise many algorithms to solve the same problem. Procedure

Algorithm Alternatives It’s possible to devise many algorithms to solve the same problem. Procedure Sat 1231 B Set day_of_week to 12/31/2000 Alternative pseudocode Set year to 2001 to determine which While (year < 2021) Do years in 2001 -2020 have { If year is a leap year New Year’s Eve on Then increment day_of_week by 2 Saturday. 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 } Both algorithms work, but which is better? Which is easier to code? Which runs more efficiently? Chapter 7 Problem Solving and Algorithm Design Page 62

Program Modularity The software development process usually involves a team of developers, so the

Program Modularity 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. Data Security Networking Capability Server Access Character Animation Customer Billing Animation Special Effects Video Game Backgrounds Game Play Artificial Intelligence Sound Effects Sound Voice Music Chapter 7 Problem Solving and Algorithm Design Page 63

Advantages of Modular Programming Modifiability Debuggability Reusability Readability It’s easier to alter or upgrade

Advantages of Modular Programming Modifiability Debuggability Reusability Readability It’s easier to alter or upgrade the program if changes can be segregated to particular modules It’s easier to diagnose and pinpoint problems with the program if it’s split into logically distinct modules Generic modules can be developed and then reused in other programs, eliminating the need to “reinvent the wheel” 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 Chapter 7 Problem Solving and Algorithm Design Page 64

Top-Down Design One common approach for designing programs is the top-down methodology. 1. Design

Top-Down Design One common approach for designing programs is the top-down methodology. 1. Design a high-level solution to the programming problem. 2. Consider each complicated subproblem as a separate programming problem. 3. Return to step #1 with each subproblem. Process Payroll Get Input Data Retrieve Timecard Data Retrieve Salary Information Retrieve Dependent Records This approach lends itself to modularity. Perform Calculations Retrieve Retirement Plans Retrieve Tax Rates Compute Gross Pay Compute Deductions Produce Output Generate Paychecks However, it may impose an artificial hierarchy on the tasks being performed. Update YTD Records Chapter 7 Problem Solving and Algorithm Design Page 65

Bottom-Up Design A newer approach for designing programs is the bottom-up methodology. 1. Separate

Bottom-Up Design 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. Physics Engine Fluid Dynamics Engine Particle Systems Engine 2. Develop cooperative programming solutions to the separate problems. Video Game Engine Math Engine Collision Detection Engine Rotational Calculation Engine Fractal Engine Artificial Intelligence Engine Intelligent Agent Engine Behavior Prediction Engine This approach produces reusable modules. However, those modules may prove difficult to cobble together to solve bigger problems. Chapter 7 Problem Solving and Algorithm Design Page 66

Chapter 8: Abstract Data Types and Algorithms Two keys to making computer software that

Chapter 8: Abstract Data Types and Algorithms 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. Chapter 8 Abstract Data Types and Algorithms Page 67

Iteration When an algorithm involves repetitive actions, iteration (i. e. , looping) may be

Iteration When an algorithm involves repetitive actions, iteration (i. e. , looping) may be a practical approach. Pseudocode to implement the search for a specific name in an alphabetized phonebook: Procedure Seq. Search(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 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 8 Abstract Data Types and Algorithms Page 68

Calling Seq. Search(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list

Calling Seq. Search(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco Mc. Gonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver 555 -7458 555 -0131 555 -3589 555 -1119 555 -3783 555 -9927 555 -2728 555 -1317 555 -1201 555 -7936 555 -7174 555 -1659 555 -2941 555 -1503 555 -8847 555 -6296 555 -5165 555 -6793 test_name is Sirius Black, so iterate again test_name is Cho Chang, so iterate again test_name is Albus Dumbledore, so iterate again test_name is Dudley Dursley, so iterate again test_name is Argus Filch, so iterate again test_name is Cornelius Fudge, so iterate again test_name is Hermione Granger, so iterate again test_name is Rubeus Hagrid, so return 555 -1317 Chapter 8 Abstract Data Types and Algorithms Page 69

Recursion Another common approach in algorithms is to employ recursion (i. e. , “divide

Recursion 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. 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) 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 8 Abstract Data Types and Algorithms Page 70

A Recursive Search Algorithm Pseudocode to recursively implement the search for a specific name

A Recursive Search Algorithm Pseudocode to recursively implement the search for a specific name in an alphabetized phonebook: Procedure Binary. Search(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 Binary. Search to the portion of phonebook after test_name Else apply Binary. Search to the portion of phonebook before test_name Notice 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 8 Abstract Data Types and Algorithms Page 71

Calling Binary. Search(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list

Calling Binary. Search(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco Mc. Gonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver 555 -7458 555 -0131 555 -3589 555 -1119 555 -3783 555 -9927 555 -2728 555 -1317 555 -1201 555 -7936 555 -7174 555 -1659 555 -2941 555 -1503 555 -8847 555 -6296 555 -5165 555 -6793 test_name is Dudley Dursley, so iterate again test_name is Cornelius Fudge, so iterate again test_name is Hermione Granger, so iterate again test_name is Rubeus Hagrid, so return 555 -1317 test_name is Gilderoy Lockhart, so iterate again Chapter 8 9 Abstract Data Types and Algorithms Page 72 77

Data Structures When interrelated information is stored in a computer’s memory, it is usually

Data Structures When 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. However, in the computer’s RAM, space for 100 integers has been allocated something like this: Address An array is an indexed list of values of the same type. Contents 00 01 : Example: int IQlist[100]; Memory cell 71 (hex 47) > Conceptually, the array looks something like this: Index 0 1 2 … 98 99 Contents 120 135 116 … 128 133 Memory cell 170 (hex AA) > 47 78 48 87 49 74 : : A 9 80 AA 85 : FE FF Chapter 8 Abstract Data Types and Algorithms Page 73

Address Contents 00 01 : Space for element (0, 0) > B 2 5

Address Contents 00 01 : Space for element (0, 0) > B 2 5 E (0, 1) > B 3 59 (0, 2) > B 4 64 (0, 3) > B 5 57 Example: int Grade. Table[3][5]; (0, 4) > B 6 5 C (1, 0) > B 7 44 (1, 1) > B 8 5 A Conceptually, the array looks something like this: (1, 2) > B 9 54 (1, 3) > BA 4 E (1, 4) > BB 56 (2, 0) > BC 4 D (2, 1) > BD 5 F (2, 2) > BE 61 (2, 3) > BF 64 (2, 4) > C 0 58 A multidimensional array is an indexed table of values of the same type, using more than one dimension. COLUMN # ROW # 0 1 2 3 4 0 94 89 100 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: : FF Chapter 8 Abstract Data Types and Algorithms Page 74

Rather than reserving a contiguous block of memory to store a list, the linked

Rather than reserving a contiguous block of memory to store a list, the linked list dynamically allocates memory as needed for list elements. Example: However, in the computer’s RAM, space for 4 integers has been allocated something like this: struct node; typedef node *node. Ptr; struct node { int value; node. Ptr next; }; 3 rd item is at address B 0 FF signifies the end of List Conceptually, the linked list looks something like this: 100 88 Contents 00 : 16 64 17 B 0 : node. Ptr List; 97 Address 4 E 5 E 4 F FF : List is located at 9 A 9 A 61 2 nd item is at address 16 9 B 16 94 : 4 th item is at address 4 E B 0 58 B 1 4 E : FF Chapter 8 Abstract Data Types and Algorithms Page 75

Relative Advantages of Arrays & Linked Lists Arrays Linked Lists Require contiguous memory Dynamically

Relative Advantages of Arrays & Linked Lists Arrays Linked Lists Require contiguous memory Dynamically locate memory Requires specific size Has flexible size Potentially wastes memory Only uses allocated space Potentially runs out of memory Expands memory as needed Insertion requires rearranging Insertion requires slight relink Deletion requires rearranging Deletion requires slight relink Indexing facilitates searching One-by-one searching required Binary search possible if sorted Sequential search only Straightforward to program Tougher to conceptualize Memory easily cleared after use Complicated garbage collection Chapter 8 Abstract Data Types and Algorithms Page 76

Comparison: Retrieving a List from a File Using an array void Get. List(int List[50],

Comparison: Retrieving a List from a File Using an array void Get. List(int List[50], int &List. Size) ) { ifstream file; char file. Name[50]; int val; Using a linked list void Get. List(node. Ptr &List) { ifstream file; char file. Name[50]; int val; node. Ptr ptr; cout << "Enter the name " << "of the file: "; cin >> file. Name; file. open(file. Name); assert(!file. fail()); cout << "Enter the name " << “of the file: "; cin >> file. Name; file. open(file. Name); assert(!file. fail()); List. Size = 0; file >> val; while ((!file. eof()) && (List. Size < 50)) ) { List[List. Size] = val; List. Size++; file >> val; } file. close(); 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 Chapter 8 Abstract Data Types and Algorithms Page 77

Comparison: Sequential Search Using an array int Search(int List[50], int List. Size, int sought.

Comparison: Sequential Search Using an array int Search(int List[50], int List. Size, int sought. Val) { int count; bool found = false; Using a linked list int Search(node. Ptr List, int sought. Val) { node. Ptr curr. Ptr; bool found = false; curr. Ptr = List; count = 0; while ((!found) && (curr. Ptr != NULL)) (count < 50)) { { if (curr. Ptr->value == if (List[count] == sought. Val) found = true; else Noteelse again that the code is almost identical, but the array version is curr. Ptr = curr. Ptr->next; } list is too long, the array can’t limitedcount++; to lists of a certain size. If the } if (found) hold it all; if it’s too short, several memory slots are wasted. if (found) return curr. Ptr->value; return List[count]; else return -1; } Chapter 8 Abstract Data } Types and Algorithms Page 78

Sorting Algorithms Somewhat more complicated than searching an alphabetized list is the problem of

Sorting Algorithms 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: Moe Uma Joe Dan Edy Quo Nan Lex Zeb Kit Sue Pez Ort Fly Cub Hal Bob Wes Ann Vin Xon Gus Ida Yul Ren Tia Chapter 8 Abstract Data Types and Algorithms Page 79

Selection Sort 1. 2. 3. 4. 5. 6. Let k equal the size of

Selection Sort 1. 2. 3. 4. 5. 6. Let k equal the size of your list Let i equal the index of the first element of your list Swap the smallest element in the last k elements with the ith element Decrease k by one Increase i by one 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 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 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 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 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 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 Chapter 8 Abstract Data Types and Algorithms Page 80

Bubble Sort 1. 2. 3. Let k equal the size of your list Let

Bubble Sort 1. 2. 3. Let k equal the size of your list Let i equal the index of the first element of your list 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 order 4. Decrease k by one 5. Increase i by one 6. 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 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 Verdict: Tougher to program, little memory waste, inefficient in general (but could easily be modified to terminate early if a swap-less pass occurs) Chapter 8 Abstract Data Types and Algorithms Page 81

Quick Sort 1. Let left. Index be the index of the leftmost element of

Quick Sort 1. Let left. Index be the index of the leftmost element of an unsorted portion of the list and right. Index be the index of the rightmost element of that portion of the list 2. Let pivot equal the value currently at index p of the list 3. Moving in from the right. Index element of the list, keep moving until a value less than pivot is found; set right. Index to the index of that value and insert it at position left. Index 4. Moving in from the left. Index element of the list, keep moving until a value greater than pivot is found; set left. Index to the index of that value and insert it at position right. Index 5. If left. Index doesn’t equal right. Index, return to step #3; otherwise, insert pivot at index left. Index and return to step #1, starting over with another unsorted portion of the list pivot: Moe Edy Zeb Hal Lex Dan Ort Bob Ida Wes Ann Uma Cub Quo Joe Kit Fly Gus Vin Xon Moe Xon Gus Vin Joe Nan Sue Quo Cub Uma Ida Yul Ren Wes Dan Ort Lex Pez Hal Zeb Tia pivot: Hal � Hal Edy Fly Gus Lex Dan Bob Cub Ida Ann Hal Cub Joe Kit Ida Fly Lex Gus Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia � pivot: Xon Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Tia Xon Vin Nan Sue Quo Uma Pez Yul Ren Wes Ort Xon Pez Zeb Yul 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: Much tougher to program, little memory waste, efficient in general (but very inefficient if the list is already almost sorted) Chapter 8 Abstract Data Types and Algorithms Page 82

A stack is a data structure that manages a list of similar items in

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. Example: Initial Stack 3 5 3 8 5 3 3 1 3 After “Push 3” After “Push 5” After “Push 8” After “Pop” After “Push 1” Chapter 8 Abstract Data Types and Algorithms Page 83

Comparison: Stack Implementations Using an array void Push(int List[50], int &Top, int item) {

Comparison: Stack Implementations Using an array 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; } Using a linked list void Push(node. Ptr &List, int item) { node. Ptr ptr = new node; ptr->value = item; ptr->next = List; List = ptr; } int Pop(node. Ptr &List) { int val = -1; if (node. Ptr != NULL) { val = node. Ptr->value; List = List->next; } return val; } Chapter 8 Abstract Data Types and Algorithms Page 84

Example Stack Application Keeping track of function calls in a third-generation programming language. Main

Example Stack Application Keeping track of function calls in a third-generation programming language. Main Program Subprogram A() Subprogram B() Subprogram C() 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; u = 15; v = 57; w = 34; cout << u << v << w << endl; B: line #3 r: 400 s: 542 t: ? A: line #4 i: 10 j: 46 k: 31 Main: line #3 x: 0 y: -2 z: ? When Main reaches the A(); step When A reaches the B(); step 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 Chapter 8 resumes and finishes. Abstract Data Types and Algorithms Page 85

A queue is a data structure that manages a list of similar items in

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. Example: F Initial Queue: After Insert 2: F/R After Insert 7: After Insert 4: 7 After Remove: F R 7 4 F R 4 2 F After Insert 5: 4 2 R 2 5 Chapter 8 Abstract Data Types and Algorithms Page 86

Comparison: Queue Implementations Using an array Using a linked list void Insert(int List[50], int

Comparison: Queue Implementations Using 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(node. Ptr &List. Front, node. Ptr &List. Rear, int item) { node. Ptr ptr = new node; ptr->value = item; ptr->next = NULL; if (List. Front == NULL) List. Front = ptr; else List. Rear->next = ptr; List. Rear = ptr; } int Remove(node. Ptr &List. Front, node. Ptr &List. Rear) { int val = -1; if (List. Front != NULL) { val = List. Front->value; List. Front = List. Front->next; } if (List. Front == NULL) List. Rear = NULL; return val; } Chapter 8 Abstract Data Types and Algorithms Page 87

Example Queue Application Job A arrives and starts processing: Job B arrives: Jobs C

Example Queue Application Job A arrives and starts processing: Job B arrives: Jobs C & D arrive: Job A completes; Job B starts processing: CPU processing Job A Keeping track of batch jobs as they arrive to be processed by a computer. Job Queue: CPU processing Job A Job Queue: B C CPU processing Job B Job Queue: C D D Chapter 8 Abstract Data Types and Algorithms Page 88

A binary tree is a hierarchical data structure that manages a collection of similar

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. Example Implementation: 8 struct node; 3 14 typedef node *node. Ptr; struct node 1 5 10 19 { int value; 7 12 16 23 node. Ptr left; node. Ptr right; 17 Example: Binary Insertion Tree }; node. Ptr 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 8 Abstract Data Types and Algorithms Page 89

Recursive Insertion into a Binary Insertion Tree void Bin_Insert(node. Ptr &Tree, int item) {

Recursive Insertion into a Binary Insertion Tree void Bin_Insert(node. Ptr &Tree, int item) { if (Tree == NULL) { node. Ptr 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); 3 } 1 Example: Where will a new node containing the integer 11 be inserted? 8 14 5 10 7 19 12 11 16 23 17 Chapter 8 Abstract Data Types and Algorithms Page 90

Recursive Traversal of a Binary Insertion Tree void Inorder(node. Ptr Tree) { if (Tree

Recursive Traversal of a Binary Insertion Tree void Inorder(node. Ptr Tree) { if (Tree != NULL) { Inorder(Tree->left); cout << Tree->value << endl; Inorder(Tree->right); } } Example: 1 3 5 7 8 10 12 14 16 17 19 23 8 Apply Inorder to this binary insertion tree: 3 1 14 5 10 7 19 12 16 23 17 Chapter 8 Abstract Data Types and Algorithms Page 91

What Does This Function Do To A Binary Tree? int Sumac(node. Ptr Tree) {

What Does This Function Do To A Binary Tree? int Sumac(node. Ptr Tree) { int leftbranch, rightbranch; if (Tree == NULL) return 0; else { leftbranch = Sumac(Tree->left); rightbranch = Sumac(Tree->right); return leftbranch + rightbranch + Tree->value; } } 125 13 5 61 34 34 22 22 0 0 51 20 0 31 7 9 9 15 0 0 0 15 0 Chapter 8 Abstract Data Types and Algorithms Page 92

Chapter 9: High-Level Programming Languages Third-generation languages (e. g. , BASIC, FORTRAN, COBOL, C)

Chapter 9: High-Level Programming Languages 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. Example: int negative (int x) { if (x < 0) return 1; else return 0; } 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! Chapter 9 High-Level Programming Languages Page 93

Compilation Source Program (in TGL) Le x ic a l A n a l

Compilation Source Program (in TGL) Le x ic a l A n a l ys i s Pa r s in g Co d e G e n e r a tio n Object Program (in Machine Language) Lexical Analysis The 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. Parsing The 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). Chapter 9 High-Level Programming Languages Page 94

Linking and Loading Since the individual portions of the TGL program are compiled as

Linking and Loading 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. Source Program Compile Object Program Lin k Load Module Lo a d Executable Program Linking A 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. Loading Finally, 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. Chapter 9 High-Level Programming Languages Page 95

Standard Source Program Organization Source programs in most third-generation languages generally follow a standard

Standard Source Program Organization Source programs in most third-generation languages generally follow a standard pattern. void main() { const int max. Count = 10; int count; int value; float sum = 0. 0; cout << “Input values” << endl; count = 0; while (count < max. Count) { 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. Chapter 9 High-Level Programming Languages Page 96

Data Types Data types are used to specify how the bit patterns used to

Data Types Data types are used to specify how the bit patterns used to represent data should be interpreted by the program. Scalar: Single-valued data types (e. g. , integer, floating-point, character, boolean) int count; float price; bool flag; Structured: Multiple-valued data types Built-In: Arrays, character strings float Caffeine. Ounces. Per. Day[7]; char chosen. Cola[] = “Pepsi”; User-Defined: Specially constructed struct Student { char name[30]; int exam. Score[5]; int quiz. Score[25]; int paper. Score[2]; char letter. Grade; }; Student FALL 111[25]; Chapter 9 High-Level Programming Languages Page 97

As Imperative Statements - Part One sig n & me I/O nt Assignment statements

As Imperative Statements - Part One sig n & me I/O nt Assignment statements are used to assign a value to a variable. x = 127; count = count + 1; E = m * c; c count E m x 186000 78 79 3309875 930000 5 290 127 Input/output statements are used to retrieve external values (input) and to file away or print information (output). Enter user’s name: MOE cout << “Enter user’s name: ”; cin >> username; data. File >> next. Data. Value; if (next. Data. Value > 0) positive. File << next. Data. Value; data. File 25 48 13 89 63 50 91 34 17 77 23 56 positive. File next. Data. Value 94 25 25 Chapter 9 High-Level Programming Languages Page 98

St Cont ate ro me l nt s Conditional statements are used to enable

St Cont ate ro me l nt s Conditional statements are used to enable alternative steps Imperative Statements - Part Two based on a condition. if (total == 0) cout << “Possible Drop”; else cout << “Total: ” << total; switch (Area. Code) { case 701: cout << “ND”; break; case 218: case 507: case 612: cout << “MN”; break; } Iterative statements are used to loop through a sequence of instructions. while (flag == false) { cin >> new. Value; if (new. Value > 0) flag = true; } total = 0; for (i = 0; { quiz. File total += } i <= 24; i++) >> score[i]; Chapter 9 High-Level Programming Languages Page 99

Imperative Statements - Part Three Procedures and functions are used to conveniently write programs

Imperative Statements - Part Three Procedures and functions are used to conveniently write programs in a modular fashion. typedef int. List[100]; void get. List(int. List list) { int count; for (count = 0; count < 100; count++) cin >> list[count]; } int maximum(int. List list) { int max. So. Far; int count; max. So. Far = list[0]; for (count = 1; count < 100; count++) if (list[count] > max. So. Far) max. So. Far = list[count]; return max. So. Far; } Pr & oced Fu nc ure tio s ns void main() { int. List IQlist; int. List SATlist; int max. IQ; int best. SAT; get. List(IQlist); max. IQ = maximum(IQlist); get. List(SATlist); best. SAT = maximum(SATlist); cout << “The highest IQ is ” << max. IQ << “ and the ” << “best SAT score is ” << best. SAT; } Chapter 9 High-Level Programming Languages Page 100

Example: What Does This Program Do? typedef int. List[4]; void get. List(int. List list)

Example: What Does This Program Do? typedef int. List[4]; void get. List(int. List list) { int count; for (count = 0; count < 4; count++) cin >> list[count]; } int drew(int. List list, int item) { int best. So. Far, best. Index, index; best. Index = -1; best. So. Far = 0; for (index = 0; index < 4; index++) if ((list[index] > best. So. Far) && (list[index] <= item)) { best. Index = index; best. So. Far = list[index]; } return best. Index; } void main() { int. List estimate; int best. Guesser; int price; cin >> price; get. List(estimate); best. Guesser = drew(estimate, price); if (best. Guesser == -1) cout << “NO WINNER”; else { cout << best. Guesser << “ WINS! ”; if (estimate[best. Guesser] == price) cout << “WITH A BONUS!!!”; } } What would be the output of this program for the following input file? 600 400 675 525 450 Chapter 9 High-Level Programming Languages Page 101

Object-Oriented Programming Early third-generation programming languages used a “procedure-oriented” approach, in which the way

Object-Oriented Programming 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 “objectoriented” approach, emphasizing what is being manipulated instead of how. Chapter 9 High-Level Programming Languages Page 102

The Three Principles of OOP • “Hide” information from objects that don’t need it.

The Three Principles of OOP • “Hide” information from objects that don’t need it. Encapsulation • 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! • Don’t “reinvent the wheel” when creating new data types. Inheritance • 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)? • Some objects are “similar”, without being the same. Polymorphism • 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. Chapter 9 High-Level Programming Languages Page 103