Download presentation
Presentation is loading. Please wait.
Published byJob Pearson Modified over 7 years ago
1
Introduction to Computer Science Basic Elements of Java A Look at Hardware and Software Unit 5
2
5- 2 What this Course is Not This is not a course on Java, even though we spend time learning this language It’s a course introducing Computer Science, which also means introducing programming (principles are better understood when they are concrete) Java is a means to what we want to accomplish, not an end in itself
3
5- 3 Course Mission Statement “To give the student the tools to develop correct, efficient, well- structured, and stylish programs, and to build a foundation for further studies in Computer Science.” - An Introduction to Computer Science with Java Kamin, Mickunas, and Reingold
4
5- 4 Why We Like Java Java is Object Oriented to the core Java is, in certain key ways, simpler than other Object Oriented languages (like C++) Java is well-suited to the Internet Java is cross-platform Java’s popularity creates its own momentum
5
5- 5 A Simple Program A Java application: class Hello { public static void main (String[ ] args) { // Say hello. System.out.println(“Hello!”); } }
6
5- 6 A Simple Program A Java application: class Hello { public static void main (String[ ] args) { // Say hello. System.out.println("Hello!"); } }
7
5- 7 The Way You Might Type It (sometimes I’ll do it this way, too) A Java application: import intro.utils.*; import java.io.*; public class Hello { public static void main (String[ ] args) { // Say hello. System.out.println( " Hello! " ); } }
8
5- 8 import intro.utils.*; import java.io.*; public class Hello { public static void main (String[ ] args) { // Say hello. System.out.println("Hello!"); } } Take it Apart import some classes class heading comment print out “Hello!” method heading
9
5- 9 Java Cares About File Names Type the program into a file named Hello.java (case matters) Java demands that the class name (here, “Hello”) must also be the base name of the file into which you put it The extension of the file must be.java Hence, Hello.java Each Class requires a separate file
10
5- 10 Steps to Nirvana Type the program into a file named Hello.java (case matters; really) Compile it Execute it The program displays the message Hello! on the screen
11
5- 11 Compilation Many high-level languages, like C, Pascal, or C++, must be compiled before they are run Compilation means translation into the native language of the computer Each computer (Wintel, Macintosh, Sun Sparc, etc.) has its own native language, so compiling the same program for each computer would create something different The statement “x = 3 + 2;” would be translated into a sequence of low-level operations
12
5- 12 Compilation C, Pascal, or C++ program Source code 1001110110101101 1101110001011010 Machine code for some specific machine Compilation
13
5- 13 Interpretation Other languages, like Lisp and SmallTalk, are interpreted They don’t get translated directly into machine language Instead, they are given to an interpreter, which is a program that performs each operation in the program on the computer The statement “x = 3 + 2;” would cause some sequence of operations to be carried out
14
5- 14 Interpretation Lisp or SmallTalk program Source code Machine instructions for some specific machine Read by an Interpreter Lisp or SmallTalk Interpreter for a Specific Machine
15
5- 15 Some Differences Compilation and Interpretation differ in many ways When machine code is generated/activated At compile time with compilation At run-time with interpretation The kind of machine code that is generated / activated Compilation can do optimizations The flexibility of development Interpreters are more flexible because you don’t have to recompile when you make changes to a program
16
5- 16 Compilation can do optimizations Let’s say you had the following lines of code: y = 7; w = 4; x = y + w; A reasonable compiler will realize what is happening and replace the last line with machine code that puts 11 into x An interpreter might carry out all the last line’s sub-operations…
17
5- 17 Where does Java fit? Compilation is efficient, but machine- specific Interpretation is flexible, but inefficient Java wanted to be efficient, but also flexible, and most important: PLATFORM INDEPENDENT (same program running on all computers) So Java is compiled and interpreted...
18
5- 18 Compilation and Interpretation A Java program can basically exist in one of two states: Source code (that’s what you are typing in) Byte code, a.class file (a translation of the original code to something closer to the machine’s language – but not any real machine’s language)
19
5- 19 Compilation and Execution public class Hello { public static void main... Source code (Hello.java file) op7 op342 op213 op431 Byte code, binary file (Hello.class file) Compilation javac Hello.java Execution java Hello Interpreter
20
5- 20 Java Byte Code (.class file)
21
5- 21 The Java Virtual Machine The Java Virtual Machine is the interpreter that reads Java byte codes and carries out real machine operations To get Java running on any kind of computer, just implement the Java Virtual Machine Presto! Java is platform independent, and flexible (interpreted), but still reasonably efficient (because Java byte code is close to machine code)
22
5- 22 Managed Code This approach in the design of Java is called “managed code” Managed code means a program (like the one you write) must be executed with a runtime environment installed in the same machine – your program cannot run without it Other examples of managed code include Visual Basic and.NET's Common Language Runtime (CLR) Compiled C or C++ programs are examples of unmanaged code “There has been a switch in the last four years toward using managed code. I'd say maybe half of the stuff that gets done now is in managed code.” - Bill Gates, CNet interview, 28.10.2003
23
5- 23 Another Program (this one takes input) We want a program that will do the following: Please type the temperature (deg C): 20 20 deg C is 68.0 deg F
24
5- 24 What the Robot World Lacked When we programmed the robot world, we had no real variables, and no real input or output In Java (as in virtually all programming languages), variables are essential Each variable has a type
25
5- 25 Input/Output in Java import intro.utils.*; import java.io.*; public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature System.out.print(" Please type the temperature (deg C): "); temperature = SimpleInput.in.readInt(); System.out.print(temperature); System.out.print(" deg C is "); System.out.print(((9.0 * temperature)/5.0 ) + 32.0); System.out.println(" deg F"); } }
26
5- 26 Helping Perceive Structure import intro.utils.*; import java.io.*; public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature System.out.print ("Please type the temperature (deg C):" ); temperature = SimpleInput.in.readInt(); System.out.print(temperature); System.out.print(" deg C is "); System.out.print(((9.0 * temperature)/5.0 ) + 32.0); System.out.println(" deg F"); } }
27
5- 27 WARNING! When you write your programs, you are to follow the course guidelines regarding style These guidelines are important; they help groups of programmers communicate with one another Do not assume that what appears in the slides is written according to course guidelines. The slides have different constraints!
28
5- 28 Variables temperature is a variable The declaration of the variable int temperature; saves a space for a value to be stored later, but doesn’t store anything there The assignment to the variable temperature = SimpleInput.in.readInt(); actually puts something in the space that was created by the declaration public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature
29
5- 29 public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature Variable Declaration temperature You don’t know what’s in there; don’t use temperature yet
30
5- 30 Simple Variable Assignment temperature = 36; temperature 36 Puts the integer 36 into temperature; now you can use temperature
31
5- 31 You Can Combine the Two Steps class Temperature { public static void main (String[ ] args) { int temperature = 36; // The Celsius temperature temperature 36
32
5- 32 import intro.utils.*; import java.io.*; public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature System.out.print ("Please type the temperature (deg C):" ); temperature = SimpleInput.in.readInt(); System.out.print(temperature); System.out.print(" deg C is "); System.out.print(((9.0 * temperature)/5.0 ) + 32.0); System.out.println(" deg F"); } } What the Program Looked Like – Getting an Integer from the User
33
5- 33 Variable Assignment – Getting an Integer from the User temperature = SimpleInput.in.readInt(); temperature SimpleInput.in Send the SimpleInput class a readInt() message, it returns an integer (that it gets from the user), which is then placed in temperature readInt() 20
34
5- 34 Special “Variables” that Remain Constant We can define a variable (a “symbolic constant”) whose value will never change, by writing final int RETIREMENT_AGE = 70; This carries out assignment at the same time as declaration (as we can do with any variable) Now RETIREMENT_AGE cannot be legally changed in the program
35
5- 35 Data Types and Expressions Different kinds of information Each kind is a “type” Java has many data types Each type has a name Each type has a set of literals Each type has a set of operations Data types in Java can be simple types or object types
36
5- 36 Different Simple Types in Java int represents integers literals like 3 and 132 operators like +, -, *, / double represents real numbers literals like 3.0, 3.14159 and 2.997925e8 The integer 3 and the double 3.0 are represented differently inside the computer
37
5- 37 More Simple Types in Java boolean Represents true and false char Represents individual characters that are typed at the keyboard
38
5- 38 Expressions An Expression represents a value that can be used in Java statements Made out of literals, variables, symbolic constants, and operations Every expression also has a type 3 + 4 + temperature (has type int) (3.0 / 4.0)* RETIREMENT_AGE (has type double) Use parentheses to establish the order of operations Can also be messages sent to an object or class, if a value is returned, like SimpleInput.in.readInt( )
39
5- 39 Type of an Expression No matter how simple or complicated an expression is, it always has a Java type, just like a variable.
40
5- 40 Where’s the Expression Go? An expression produces a value, which is then often used in an assignment statement So typically, the expression is on the right hand side of the assignment statement: temperature = 36; temperature = (x / 7) + y; temperature = SimpleInput.in.readInt() ;
41
5- 41 The Order of Assignment In general, the computer evaluates the expression on the right side, and places that value in the variable on the left side, replacing the old value. So: temperature = temperature + 10; is completely legal; it adds 10 to the value of temperature Can also be written: temperature += 10;
42
5- 42 Increment/Decrement Two special cases: incrementing and decrementing cent++; is the same as cent = cent + 1; cent--; is the same as cent = cent - 1;
43
5- 43 One of Your Own Kind, Stick to Your Own Kind Java is very strict about data types and assignments Java only puts into a variable a value of the appropriate type Expressions having an integer value can go into an integer variable, etc. You can’t do this: int i; double x = 3.0; i = 10.3 * x;
44
5- 44 Special Case You can assign an integer expression to a double variable The integer is converted to a double without loss of information, so it is done automatically You can do this: int i = 3; double x; x = 10 * i;
45
5- 45 Converting Values from One Type to Another The cast operation lets you explicitly convert one type to another You can do this: int i; double x = 3.0; i = (int) (10.3 * x); The cast (int) takes the expression that follows it and converts it into an integer by removing any fractional part; i is assigned the integer value 30
46
5- 46 Object Types in Java The existence of a class in Java lets you have variables that are of new types, rather than just simple types (Java gives us simple types int, double, boolean, char, etc.) Every class C defines a set of values called objects of type C (that is, C is a class name) Just as you define a new variable to be of type int, you can define a new variable (object) to be of type C
47
5- 47 Defining Objects of Type C C u, v, w; declares u, v, and w to be objects of type C (or “variables of type C ” or “instances of type C ”) This is similar to writing int a, b, c; to declare a, b, and c to be variables of type int Object type Simple type
48
5- 48 One of these things, Is not like the other If C and D are two different classes, their objects have different types They can’t be assigned to one another If u is an object of type C, and: D t; // an object of type D we cannot do either of the following: u = t; t = u; We also cannot do something like u = 10;
49
5- 49 Constructors Declaring a new object just tells the system the type of the object: C u; To create the object, we use a constructor: u = new C( arguments ); A constructor is a special method of the class that creates and initializes the new object; it has the same name as the class It is the way to create objects
50
5- 50 Creating Objects and Filling them with Values This looks a lot like how we created objects in the robot world Yes, the two statements (declaration and creation) can be combined: C u = new C( arguments ); That’s all we were doing in the robot world – combining declaration (declaring the type of the object) with constructing a new object
51
5- 51 They Look the Same But They are Different The first C and the second C fulfill two different roles The first C tells the type of the object variable (like int tells the type of a simple variable) The second C is a call to the method C inside the class C that is the class’ constructor, and creates the object C u = new C( arguments );
52
5- 52 Methods within an Object If u is an object of class C, and class C has a method called “ display ”, then we’ll trigger a method in u by writing: u.display( arguments ) You’ve already seen the same thing in the robot world We’re sending the object u a message “ display ” with arguments
53
5- 53 You can also send messages to Classes Unlike in the robot world, there are cases when a class is sent a message, rather than an object Later we’ll talk about when we do this kind of thing
54
5- 54 The String Class This is an important predefined, special class that we are given as part of the Java system Can be used as follows: Stringt1 = "To be ", t2 = "or not to be."; System.out.print(t1 + t2); prints out: To be or not to be. Notice that this is a special case – we are creating objects without explicitly calling a constructor
55
5- 55 The String Class has some useful Methods Strings have a method called “ length ”: Stringt1 = "To be ", t2 = "or not to be."; t1.length( ) then is an expression that returns the integer 6, the number of characters in the object t1 We send the object t1 a message length( ), and get back the integer 6; we are asking the object about itself; that’s common
56
5- 56 Fun with Strings and + System.out.print("4" + "5");//prints: 45 System.out.print("4" + 5); //prints: 45 System.out.print(4 + 5);//prints: 9 System.out.print("4" + "005"); //prints: 4005 System.out.print("4" + 005);//prints: 45 System.out.print("4" * 5);//error! An integer concatenated to a string is automatically converted to a string
57
5- 57 Statements We’ve seen two Java programs that are sequences of statements, each statement either assigning a value to a variable, or an executable statement that prints output System.out.print(" Please type the temperature (deg C): "); temperature = SimpleInput.in.readInt( ); There are of course other kinds of statements, conditionals ( if, if/else ), and iterative statements (like for and while loops)
58
5- 58 Perceiving Structure, Again import intro.utils.*; import java.io.*; public class Temperature { public static void main (String[ ] args) { int temperature; // The Celsius temperature System.out.print(" Please type the temperature (deg C): "); temperature = SimpleInput.in.readInt(); System.out.print(temperature); System.out.print(" deg C is "); System.out.print(((9.0 * temperature)/5.0 ) + 32.0); System.out.println(" deg F"); } }
59
5- 59 Three Ways of Using Methods in your Programs (we’ll understand why, later) Every execution starts with some “ static ” method main( ) That main( ) method might be in the same class as your other methods, or it might be in a separate class (a so-called “driver”) If main( ) is in the same class as your other methods, and you use those other methods directly from main( ) (i.e., without creating an object), then those other methods must also be “ static ” This is also true of class variables used directly from main( )
60
5- 60 Warning!!! The following programs are not good programming style, they are just examples of when to use the keyword “ static ”!
61
5- 61 1. Direct (static) use (not real OOP) class Temperature { public static int firstTemp; public static void main (String[ ] args) { int secondTemp; firstTemp = 7; secondTemp = firstTemp + 9; printMessage( ); System.out.println("The sum is " + secondTemp); } public static void printMessage ( ) { System.out.println("This is a silly program."); } }
62
5- 62 1. Direct (static) use (not real OOP) class Temperature { public static int firstTemp; public static void main (String[ ] args) { int secondTemp; firstTemp = 7; secondTemp = firstTemp + 9; printMessage( ); System.out.println("The sum is " + secondTemp); } public static void printMessage ( ) { System.out.println("This is a silly program."); } }
63
5- 63 A Second Way of Using Methods in your Programs Even if the main( ) method is in the same class as your other methods, you can (instead) create an object with a name, and send messages to the object Then those other methods (or variables) should not be “ static ” This is similar to what you did in the robot world…that is, using real objects in your program
64
5- 64 2. Use via an Object class Temperature { public int firstTemp; public static void main (String[ ] args) { int secondTemp; Temperature bill = new Temperature( ); bill.firstTemp = 7; secondTemp = bill.firstTemp + 9; bill.printMessage( ); System.out.println("The sum is " + secondTemp); } public void printMessage ( ) { System.out.println("This is a really silly program."); } }
65
5- 65 2. Use via an Object class Temperature { public int firstTemp; public static void main (String[ ] args) { int secondTemp; Temperature bill = new Temperature( ); bill.firstTemp = 7; secondTemp = bill.firstTemp + 9; bill.printMessage( ); System.out.println("The sum is " + secondTemp); } public void printMessage ( ) { System.out.println("This is a really silly program."); } }
66
5- 66 class StairSweeper extends BasicRobot { public static void main[String[ ] args] { StairSweeper larry = new StairSweeper(2, 1, East, 0); larry.climbStair( ); larry.pickBeeper( ); larry.climbStair( ); larry.pickBeeper( ); larry.climbStair( ); larry.pickBeeper( ); larry.turnOff( ); } void turnRight( ) { turnLeft( ); turnLeft( ); turnLeft( ); } void climbStair( ) { turnLeft( ); move( ); turnRight( ); move( ); } }
67
5- 67 A Third Way of Using Methods in your Programs Commonly, the main( ) method will be in a different class (and file) from your other methods This driver class might be supplied by the metargelim, or you might write it yourself It will create an object with a name, and send messages to the object And those object’s methods (or variables) will not be “ static ” This is also similar to what you did in the robot world…
68
5- 68 3. Use via an Object in Separate Class class Driver { public static void main (String[ ] args) { int secondTemp; Temperature bill = new Temperature( ); bill.firstTemp = 7; secondTemp = bill.firstTemp + 9; bill.printMessage( ); System.out.println("The sum is " + secondTemp); }
69
5- 69 3. Use via an Object in Separate Class class Temperature { public int firstTemp; public void printMessage ( ) { System.out.println("This is a very silly object."); } } Those are the constraints for using “ static ” in your Java programs. We will understand what “ static ” really means, later in the course
70
5- 70 REMINDER – Importing Class Definitions Instead of putting all these things together in one file, we could break them up as follows: class StairSweeper extends BasicRobot { void turnRight( ) { turnLeft( ); turnLeft( ); turnLeft( ); } void climbStair( ) { turnLeft( ); move( ); turnRight( ); move( ); } } A file called StairSweeper.java import StairSweeper; public static void main[…] { StairSweeper larry = new StairSweeper(2, 1, East, 0); larry.climbStair( ); larry.pickBeeper( ); larry.climbStair( ); larry.pickBeeper( ); larry.climbStair( ); larry.pickBeeper( ); larry.turnOff( ); } A file called Driver.java
71
5- 71 What Will NOT Work class Box { public int height; public int width; public static void main (String[ ] args) { System.out.println("The height is " + height); System.out.println("The width is " + width); } The static main method cannot use the non- static variables “ height ” and “ width ” directly (that is, without creating an object)
72
5- 72 Debugging a Program We’re going to walk through a debugging of a sample program
73
5- 73 Write and Debug a Program Compute the total cost of a coffee order ( (Price per pound) x Weight ) + Shipping Shipping = ((Shipping Rate per pound) x Weight ) + Fixed handling fee Price per pound and Weight vary Shipping Rate per pound and handling fee are fixed
74
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final int RATE_PER_POUND = 1.25, FIXED_FEE, int priceperPound, weight, shippingCost, coffeeCost; System.out.println(“Enter price per pound: ); pricePerPound = SimpleInput.in.readInt(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shipingCost = RATE_PER_POUND+weight +FIXED_FEE; totalPrice = priceperPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shipingCost); System.out.println(“Total cost is “ totalPrice); } }
75
ERROR
76
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final int RATE_PER_POUND = 1.25, FIXED_FEE; int priceperPound, weight, shippingCost, coffeeCost; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readInt(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shipingCost = RATE_PER_POUND+weight +FIXED_FEE; totalPrice = priceperPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shipingCost); System.out.println(“Total cost is “ totalPrice); } }
77
ERROR
78
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final int RATE_PER_POUND = 1.25, FIXED_FEE; int priceperPound, weight, shippingCost, coffeeCost; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readInt(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shipingCost = RATE_PER_POUND+weight +FIXED_FEE; totalPrice = priceperPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shipingCost); System.out.println(“Total cost is “ + totalPrice); } }
79
ERROR
80
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final double RATE_PER_POUND = 1.25, FIXED_FEE = 1.95; int pricePerPound, weight, shippingCost, coffeeCost, totalPrice; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readInt(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shippingCost=RATE_PER_POUND+weight +FIXED_FEE; totalPrice = pricePerPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shippingCost); System.out.println(“Total cost is “ + totalPrice); } }
81
ERROR
82
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final double RATE_PER_POUND = 1.25, FIXED_FEE = 1.95; double pricePerPound, weight, shippingCost, coffeeCost, totalPrice; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readInt(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shippingCost=RATE_PER_POUND+weight +FIXED_FEE; coffeeCost = pricePerPound * weight; totalPrice = pricePerPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shippingCost); System.out.println(“Total cost is “ + totalPrice); } }
83
5- 83 We run the program Enter price per pound: 8.95 java.lang.NumberFormatException: 8.95 at java.lang.Integer.parseInt(Integer.java) at java.lang.Integer. (Integer.java) at SimpleInput.in.readInt… at CoffeeOrder.main(CoffeeOrder.java… We’ve got a problem. We tried to read a double by sending SimpleInput.in the readInt() message.
84
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final double RATE_PER_POUND = 1.25, FIXED_FEE = 1.95; double pricePerPound, weight, shippingCost, coffeeCost, totalPrice; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readDouble(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shippingCost=RATE_PER_POUND+weight +FIXED_FEE; coffeeCost = pricePerPound * weight; totalPrice = pricePerPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shippingCost); System.out.println(“Total cost is “ + totalPrice); } }
85
5- 85 We Run the Program Again Enter price per pound: 8.95 Enter number of pounds: 3 Coffee total is 26.849999999999998 Shipping cost is 6.2 Total cost is 33.05 Great! Only one problem. The total cost is $0.50 too high.
86
import intro.utils.*; class CoffeeOrder { public static void main (String[ ] args) { final double RATE_PER_POUND = 1.25, FIXED_FEE = 1.95; double pricePerPound, weight, shippingCost, coffeeCost, totalPrice; System.out.println(“Enter price per pound: “); pricePerPound = SimpleInput.in.readDouble(); System.out.print(“Enter number of pounds: “); weight = SimpleInput.in.readInt(); shippingCost=RATE_PER_POUND*weight +FIXED_FEE; coffeeCost = pricePerPound * weight; totalPrice = pricePerPound * weight + shippingCost; System.out.println(“Coffee total is “ + coffeeCost); System.out.println(“Shipping cost is “ + shippingCost); System.out.println(“Total cost is “ + totalPrice); } }
87
5- 87 We Run the Program One Last Time Enter price per pound: 8.95 Enter number of pounds: 3 Coffee total is 26.849999999999998 Shipping cost is 5.7 Total cost is 32.55 That’s good enough for now.
88
5- 88 Models You can think about objects in many different ways You can think about them based on their responses to actions You can think about it based on what is “happening inside” Even what is “happening inside” can be thought of in different ways
89
5- 89 Models How you look at things can differ depending on what you want to do How much understanding you need depends on what you want to do You can often relate to lower levels, different models, as “black boxes” – that’s a good thing!
90
5- 90 When Good Models Go Bad Generally, though, there is a mismatch between models This becomes especially clear when something goes wrong…and the model’s mismatch becomes confusing…
91
5- 91 A lock and key Put the key in Turn it one way, the door is unlocked Turn it the other way, the door is locked
92
5- 92 A lock and key A lock has many different parts We could think about it based on how the different parts work together
93
5- 93 A lock and key More detail than perhaps you need to know There is also the physics description – springs, forces, friction…
94
5- 94 And when something goes wrong… What if the key becomes damaged? Certain kinds of damage don’t matter (a key can be shaved thinner, and it will still work) Certain kinds of damage keep it from working (a key’s tooth is broken and it won’t work)
95
5- 95 Things got even harder with electricity – Transparent vs. Opaque Functionality At least there used to be a visible connection between physical things and what they did a butter churn a loom a watch a lock and key The coming of electrical power changed that fundamentally
96
5- 96 The Computer The computer is the supreme example of opaque function Looking into the box does not help us to understand what is going on The best way to understand computers (perhaps the only way) is to understand the logical layers out of which they are built
97
5- 97 The Layers of Computing Underlying hardware CPU Memory Hard diskKeyboard Machine Layer Software Assembly Languages Machine Languages Micro- Programs System Layer Software UNIXWindowsApple System Application Layer Software CompilerGamesUtilitiesBrowser Screen
98
5- 98 Binary Representation Everything in the computer is represented as numbers Everything That includes integers, floating point numbers, characters, commands, variables, symbols… And, in fact, it represents them as the simplest kind of numbers there are, binary numbers
99
5- 99 But First, Decimal Numbers 10 digits, from 0 through 9 Each column represents a power of 10: 10 0, 10 1, 10 2, 10 3, etc. (that is, 1’s, 10’s, 100’s, 1000’s, etc.) 3248 is actually 8 1’s, plus 4 10’s, plus 2 100’s, plus 3 1000’s 10 0 10 1 10 2 10 3 But this works just as well if we use a different number of digits.
100
5- 100 Binary Numbers 2 digits, from 0 through 1 Each column represents a power of 2: 2 0, 2 1, 2 2, 2 3, etc. (that is, 1’s, 2’s, 4’s, 8’s, etc.) 1011 is actually 1 1’s, plus 1 2’s, plus 0 4’s, plus 1 8’s (which is the same as 11 in the decimal system) 2020 2121 2 2323
101
5- 101 Internal Representation The memory in a computer consists of lots of 0’s and 1’s; each binary digit is called a “bit” 8 bits is called a “byte” They are organized into “words”, whose size depends on the specific computer (usually 32 bits or 64 bits, that is, 4 bytes or 8 bytes)
102
5- 102 Computer’s Internal Memory (Random Access Memory – RAM)
103
5- 103 Computer’s Internal Memory (RAM) 32 bits per word (each bit holds a 0 or a 1)
104
5- 104 Computer’s Internal Memory (RAM) 32 bits per word (each bit holds a 0 or a 1) 34 words in this picture (there could be millions)
105
5- 105 How Much Can be Represented in one Byte? Each column represents a power of 2: 2 0, 2 1, 2 2, 2 3, 2 4, 2 5, 2 6, 2 7 (that is, 1’s, 2’s, 4’s, 8’s, 16’s, 32’s, 64’s, 128’s) 1001 1011 is actually 1 1’s, plus 1 2’s, plus 0 4’s, plus 1 8’s, plus 1 16’s, plus 0 32’s, plus 0 64’s, plus 1 128’s (i.e., 155 decimal). The smallest number is 0, the largest number is 11111111, i.e., 255, i.e., 2 8 - 1 2020 2121 2 2323 2424 2525 2626 2727
106
5- 106 Why Are “8 bits” Interesting? 8 bits is sufficient to represent the numbers from 0 to 255 (enough for a complete table of English and European letters), so that’s why it became a standard grouping of bits
107
5- 107 More Bytes With 8 bits, 256 separate numbers If you had 10 bits, the biggest number would be 2 10 -1, or 1023 – you have 1,024 separate numbers That’s close to a thousand, and we love using binary numbers, so we’ll call that a kilobyte (or KB) – about a thousand bytes With 10 bits, I could refer to 1024 separate places in memory A kilobyte of text is 1024 separate characters
108
5- 108 More Bytes If you had 20 bits, the biggest number would be 2 20 -1, or 1048575 – you have 1,048,576 separate numbers That’s close to a million, and we love using binary numbers, so we’ll call that a megabyte (or MB) – about a million bytes With 20 bits, I could refer to 1048576 separate places in memory, for example A megabyte of text is 1048576 separate characters
109
5- 109 More Bytes If you had 30 bits, the biggest number would be 2 30 -1, or 1073741823 – you have 1,073,741,824 separate numbers That’s close to a billion, and we love using binary numbers, so we’ll call that a gigabyte (or GB) – about a billion bytes With 30 bits, I could refer to 1073741824 separate places in memory, for example A gigabyte of text is 1073741824 separate characters
110
5- 110 More Bytes If you had 40 bits, the biggest number would be 2 40 -1, or 1099511627775 – you have 1,099,511,627,776 separate numbers That’s close to a trillion, and we love using binary numbers, so we’ll call that a terabyte – about a trillion bytes With 40 bits, I could refer to 1099511627776 separate places in memory, for example A terabyte of text is 1099511627776 separate characters
111
5- 111 How Much Room to Represent Things Digitally, in Bytes A character takes 1 byte An email message (represented as plain text) might take up a kilobyte (approximately 40 characters per line x 25 lines) A book (represented as plain text) might take up a megabyte (approximately 70 characters per line x 45 lines per page x 300 pages) 100 megabytes could hold 2 volumes of encyclopedias 1 Gigabyte could hold the contents of about 10 meters of books on a shelf 100 Gigabytes could hold the entire library floor of academic journals
112
5- 112 How Much Room to Represent Things Digitally, in Bytes A terabyte could hold 1,000 copies of the Encyclopedia Britannica Ten terabytes could hold the printed collection of the Library of Congress A petabyte is approximately 1,000 perabytes or one million gigabytes. 1 petabyte could hold approximately 20 million 4-door filing cabinets full of text An exabyte is approximately 1,000 petabytes. “5 exabytes would be equal to all of the words ever spoken by mankind.”
113
5- 113 How Much Room to Represent Things Digitally, in Bytes A minute of AVI digital video (uncompressed) – 200 MB One minute of a song in MP3, sampled at 128kbps (kilobits per second) – 1 MB One minute of a song on a CD – 10 MB A typical CD (approximately 45 minutes) – 450 MB Maximum on a CD: 783,216,000 bytes (approx. 747 MB)
114
5- 114 How Do I Represent Music with 0’s and 1’s? Analog sound signal:
115
5- 115 How Do I Represent Music with 0’s and 1’s? Another analog sound signal: I can approximate that with discrete sampling, assigning a number to each sample:
116
5- 116 How Do I Represent Music with 0’s and 1’s? The more samples I take, and the more gradations there are, the greater accuracy I have of the original analog signal:
117
5- 117 How Do I Represent Music with 0’s and 1’s? Maximum on a CD (this is the standard): 44,100 samples per channel per second 2 bytes per sample means 2 16 gradations, i.e., 65536 gradations – good fidelity 44,100 samples/channel/second x 2 bytes/sample x 2 channels (stereo) x 74 minutes x 60 seconds/minute = 783,216,000 bytes (approx. 747 MB)
118
5- 118 Standards for Digitization For this to work, there must be an agreed upon way of representing characters, music, graphics, floating point numbers, even integers, using binary numbers So government bodies and companies get together and agree on a CD standard, a DVD standard, an MP3 standard, a JPEG standard, a GIF standard, an ASCII standard, etc. Or they don’t “The great thing about standards is that there are so many of them.” (Joke)
119
5- 119 ASCII Table (uses 8 bits)
120
5- 120 ASCII Table (not really…)
121
5- 121 Symbol Font Table
122
5- 122 Microsoft Windows Codepage : 1255 (Hebrew)
123
5- 123 Unicode To represent all of the world’s languages, you need more than 256 places in a table – you need more than 8 bits to represent a character The Unicode standard makes use of 32 bits to represent everything in a single table But there are clever ways to keep most text represented by a single byte The Hebrew table in Unicode occupies the range 0590 to 05FF
124
5- 124 Hexadecimal Notation Sometimes for convenience sake, 4 binary bits get grouped together and represented by a symbol between 0 and 9, or between A and F (where A represents decimal 10 and F represents decimal 15) So: 1001 is written hexadecimal 9 1010 is written hexadecimal A (= decimal 10) 1110 is written hexadecimal E (= decimal 14) 1001 1110 is written hexadecimal 9E (= 158)
125
5- 125 Hiragana – Range 3040 to 309F
126
5- 126 Internal Representation A computer word of 32 bits is “just” a string of 1’s and 0’s: 10011001111011010101010010110110 It might represent any one of a number of things: 4 characters An integer Half of a double (floating point number) A computer command in machine language
127
5- 127 Internal Representation 4 characters 10011001111011010101010010110110 An integer 10011001111011010101010010110110 Half of a double (floating point number) 10011001111011010101010010110110 A computer command in machine language 10011001111011010101010010110110 The computer system itself must keep track of what the bits represent --- or allow a program to decide at runtime. “machine language”? What’s that?
128
5- 128 Machine language – Mark I
129
5- 129 Machine Language 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
130
5- 130 Binary (half) Addition 0 plus 0 is 0 0 plus 1 is 1 1 plus 0 is 1 1 plus 1 is 0, carry a 1 to next column 1100 + 1 ------ 1101 Only good for first column.
131
5- 131 Binary (full) Addition, Handles Other Columns 0 plus 0 plus 0 is 0 0 plus 0 plus 1 is 1 0 plus 1 plus 0 is 1 0 plus 1 plus 1 is 0, carry a 1 to next column 1 plus 0 plus 0 is 1 1 plus 0 plus 1 is 0, carry a 1 to next column 1 plus 1 plus 0 is 0, carry a 1 to next column 1 plus 1 plus 1 is 1, carry a 1 to next column 11 + 11 ----- 110 These actions are carried out by circuits in the computer.
132
5- 132 Binary (half) Adder, Circuit 0 plus 0 is 0 0 plus 1 is 1 1 plus 0 is 1 1 plus 1 is 0, carry a 1 to next column AND XOR AND truefalse true false XOR truefalse truefalsetrue falsetruefalse Where true is represented by a 1 (high voltage) and false is represented by a 0 (low voltage)
133
5- 133 Binary (full) Adder, Circuit AND XOR OR XOR OR Calculating A plus B, where C is the “carry bit” from the previous column (1 or 0) There are many equivalent circuits that compute this truth table / function
134
5- 134 0’s and 1’s What represents the 0’s and 1’s? It can be (and has been) many things… Voltages, magnetic fields of various kinds, physical relays that are open or closed, vacuum tubes, transistors in different states… Anything that can be in two well- differentiated states, and that can be easily/quickly switched between the states.
135
5- 135 The Layers of Computing Underlying hardware CPU Memory Hard diskKeyboard Machine Layer Software Assembly Languages Machine Languages Micro- Programs System Layer Software UNIXWindowsApple System Application Layer Software CompilerGamesUtilitiesBrowser Screen
136
5- 136 The "Classic" Computer Architecture CPU Memory Hard disk Keyboard - Input Screen - Output
137
5- 137 The "Classic" Typewriter Architecture Keyboard - Input Paper - Output Direct Mechanical Action
138
5- 138 What Makes the Computer Different? Memory Short-term Long-term Programmable Multi-purpose Communication-enabled
139
5- 139 History People have wanted to have machines to help them calculate for thousands of years These aspirations began to be more grandiose with the advent of the industrial revolution
140
5- 140 “Calculating Machine” or “Mechanical Brain”? At first, people thought of these machines as very fast calculators The desire was to make them be programmable, general purpose calculators One turning point was to realize that the program could be represented as a number, and placed into the computer’s memory, making it much easier to re-program the very fast calculator
141
5- 141 “Calculating Machine” or “Mechanical Brain”? But the really important turning point (which did not happen all at once) was to realize that these machines could be more than calculators – if almost everything could be represented as numbers, and they could manipulate numbers, they could carry out all sorts of actions that we don’t normally associate with numbers
142
5- 142 ASCC Mark I, "Automatic Sequence-Controlled Calculator" Built at Harvard by Howard Aiken, completed January 1943 Approaching architecture of a modern computer Used mechanical electromagnetic relays for storing numbers and doing calculations The machine was 51 feet long, weighed 5 tons, and incorporated 750,000 parts. It included 72 accumulators
143
5- 143 ENIAC, the “first large-scale, all-electronic, general purpose, digital computer” Eckert and Mauchly, University of Pennsylvania, November 1945 ENIAC's architecture resembles that of the Harvard Mark I, but its components are entirely electronic, incorporating 17,468 vacuum tubes The machine weighs 30 tons, covers about 1000 square feet of floor, and consumes 130 kilowatts of electricity; it uses vacuum tubes
144
5- 144 ENIAC The machine incorporates 20 accumulators (the original plan was for 4). Each accumulator stores a 10-digit number, using 10 bits to represent each digit. A separate unit can perform multiplication (in about 3 milliseconds), while another does division and square roots
145
5- 145 ENIAC A card reader is available to input data values, and there is a card punch for output The program is set up on a plugboard --- this is considered reasonable since the same or similar program would generally be used for weeks at a time The ENIAC's clock speed is 100 kHz
146
5- 146 ENIAC
147
5- 147 More ENIAC
148
5- 148 EDVAC, "Electronic Discrete Variable Automatic Computer" Oppenheimer and von Neumann EDVAC was the first stored program computer
149
5- 149 EDSAC, Electronic Delay Storage Automatic Computer Based on EDVAC report, first full-scale operational stored program computer, May 1949 16 tanks of mercury give a total of 256 35- bit words (or 512 17-bit words) The clock speed of the EDSAC is 500 kHz; most instructions take about 1500 ms to execute Its I/O is by paper tape, and a set of constant registers is provided for booting
150
5- 150 Things You Wish You Hadn’t Said The United States will need a total of six electronic digital computers – Howard Aiken, developer of Mark I, 1947 “Computers in the future may weigh no more than 1.5 tons” – article in Popular Mechanics, 1949
151
5- 151 Lots More History Brattain, Bardeen, and Shockley invent the transistor, which eventually replaces vacuum tubes, Dec. 1947 Noyce invents the integrated circuit, which puts multiple connected transistors onto a chip, January 1959 Hoff invents programmable computer on a chip, Intel 4004, 1970
152
5- 152 Inventor of Intel 4004 Computer-on- a-Chip, Marcian Hoff
153
5- 153 Intel 4004 2250 transistors on the chip Processed 4 bits of data at a time 600,000 operations a second Followed by (in Intel's line of chips) the Intel 8008 the 8080, the first chip that made a personal computer possible the 8088, and the 8086, and the 80286, 80386, 80486, Pentium, Pentium II, III, IV...
154
5- 154 Underlying Hardware—CPU Central Processing Unit (CPU) — speed measured using many different benchmarks Integer performance, SPECint*_base2000 Floating point performance, SPECfp*_base2000 Entertainment benchmarks, internet benchmarks, … Pentium, Pentium II, III, IV, PowerPC, Sun Sparc See, for example, http://www.intel.com/performance/resources/desktop/index.htm for information about Pentium IV performance http://www.intel.com/performance/resources/desktop/index.htm
155
5- 155 Underlying Hardware—RAM Random Access Memory (RAM) — size measured in megabytes or gigabytes Holds programs while they are being run 2003 desktop computer might have from 256 to 1024 megabytes of RAM; more powerful computers can have much more RAM
156
5- 156 Underlying Hardware—Hard Disk Hard disk holds programs “permanently” (even while power is off) 2003 desktop computer might have between 60 to 200 gigabytes of hard disk storage
157
5- 157 Underlying Hardware — Removable Media Floppy disks, writeable CDs (CD-R) and DVDs (DVD-R, DVD+R, DVD-RW, DVD+RW) and tape allow data to be backed up or transferred from one computer to another Zip drives, 1 gigabyte Jaz drives (Iomega), dual purpose MP3 hard-disk based players like the iPod, flash memory up to 128MB or 256MB are common (MemoryStick, CompactFlash, Secure Digital, MultiMediaCard), …
158
5- 158 Underlying Hardware — Input/Output Devices Input devices, like a keyboard and a mouse (and a microphone, and a joystick, and a trackball, and a pen, and a scanner, and…) Output devices, like a screen and a printer (and a speaker, and a plotter, and a laser printer, and…)
159
5- 159 A Brief Diversion Doug Engelbart, the inventor of the mouse (and windowed interfaces, and more): http://www2.bootstrap.org/history.htm The first mouse:
160
5- 160 Input Devices that didn't take off The chord key set:
161
5- 161 Names you probably don't know Short History of the Internet http://www.umr.edu/~dunaw/net-history.html Paul Baran, of the RAND Corporation, commissioned by the U.S. Air Force to do a study on how it could maintain its command and control over its missiles and bombers, after a nuclear attack. Suggested a packet-switched network. http://www.umr.edu/~dunaw/net-history.html Leonard Kleinrock, UCLA researcher who connects computer to switch to another computer, 2 September 1969 Ray Tomlinson, BBN engineer who invents inter-machine email in 1972, "a quick hack", chooses the @ http://www.pretext.com/mar98/features/story2.htm
162
5- 162 Typical Desktop Hardware Configuration, 2003 Pentium IV processor, running at 3.06 GHz 1 gigabyte of RAM Flat screen LCD 15” color monitor Built-in ethernet and modem CD-RW, DVD-RW drives 160 gigabyte hard disk Approximate cost in U.S.:$1300
163
5- 163 Typical Desktop Hardware Configuration, 1984 IBM AT 80286 processor, running at 6 MHz 256 KB of RAM, expandable to 3MB using five expansion cards Monochrome monitor (color graphics card) 20 MB hard disk Approximate cost in U.S.:$6600
164
5- 164 Hardware Comparison, 1984 –2003 IBM AT 80286 processor, running at 6 MHz 256 KB of RAM, expandable to 3MB using five expansion cards Monochrome monitor (color graphics card) 20 MB hard disk Approximate cost in U.S.:$6600 Pentium IV processor, running at 3.06 GHz 1 gigabyte of RAM Flat Screen LCD 15” color monitor Built-in ethernet and modem CD-RW, DVD-RW drives 160 gigabyte hard disk Approx. cost in U.S.: $1300 Price/performance ratio improvement, factor of over 8000
165
5- 165 Moore’s Law The computing power available at a fixed price will double every 18 months “Moore…affirmed he never said transistor count would double every 18 months, as is commonly said. Initially, he said transistors on a chip would double every year. He then recalibrated it to every two years in 1975. David House, an Intel executive at the time, noted that the changes would cause computer performance to double every 18 months. “House actually came close. Computer power is doubling around every 20 months. Nonetheless, ‘House said 18 months, not me,’ Moore said. “The observation has also proved much more resilient than Moore thought. ‘I never expected it to be precise. It turned out to be much more precise than I ever imagined,’ he said.” – CNet, 11 Feb 2003
166
5- 166 The Meaning of Exponential Growth This has been true for over the last 35 years, and will continue to be true in coming years Most people cannot grasp the real meaning of exponential growth, confusing it with linear growth at a sharp angle over the short term
167
5- 167 Exponential Growth, Doubling Every Time Interval, 1, 2, 4, 8, 16, 32, …
168
5- 168 Exponential Growth, Doubling Every 18 months, 1973 = 1, 2003 = 1048576
169
5- 169 If Cars Improved the Way Computers Do A Rolls Royce would cost $1 and travel 5000 kilometers on a liter of gasoline But it would be too small to get into Really: $20,000 in 1968 $5,000 in 1971 $1,250 in 1974 $0.0025 in 2003
170
5- 170 The Future of the IPod Hard disk holding 40 GB $400 in 2003 $100 in 2006 $25 in 2009 $6.25 in 2012 ~ $1.50 in 2015 ~ $0.40 in 2018
171
5- 171 Why We Don’t Notice It We are focused on short periods, where the difference between linear and exponential is obscured
172
5- 172 Exponential Growth, Doubling Every 18 months, 1973 = 1, 2003 = 1048576
173
5- 173 But the Future is Just as Amazing 2003 = 1 2006 = 4 2018 = 1024
174
5- 174 Two Curves powerfulweak thennow The Hardware Curve powerful weak thennow The Software Curve
175
5- 175 Two Major Developments The two biggest developments in the computer industry in the last 5 years: The transition of the computer from a computing device to a communications and computing device The ever-shrinking, ever-cheaper computing power has led to “computers everywhere”, digital appliances, embedded and standalone
176
5- 176 People are Thinking about the End of Moore’s Law… Intel researchers publish paper in Proceedings of the IEEE, November 2003, predicting fundamental limits of Moore’s Law to be reached in roughly 20 years http://news.com.com/2100-7337-5112061.html?tag=nefd_lede “Manufacturers will be able to produce chips on the 16-nanometer manufacturing process, expected by conservative estimates to arrive in 2018, and maybe one or two manufacturing processes after that, but that’s it…In chips made on a 16-nanometer technology process, the transistor gate will be about 5 nanometers long” (a nanometer is a billionth of a meter) This is a limitation of physics (tunneling of electrons through the gate of a transistor), not of any particular material used to make the transistor
177
5- 177 Where Does it End? Two papers by Harvard and Cornell researchers in the June 13, 2002 issue of the journal Nature described a breakthrough in miniaturization: researchers have created transistors whose switching components are literally single atoms (but they lack “gain” and work just at very low temperatures). What happens when the physical limits are reached? Does the hardware curve straighten out? Do new technologies (optical computing, DNA computing, quantum computing) provide new solutions?
178
5- 178 The Layers of Computing Underlying hardware Machine Layer Software Assembly Languages Machine Languages Micro- Programs System Layer Software UNIXWindowsApple System Application Layer Software CompilerGamesUtilitiesBrowser CPU Memory Hard diskKeyboard Screen
179
5- 179 Machine Layer Software Machine language instructions — built into the computer, a language of 1’s and 0’s Assembly language instructions — use brief English-like mnemonics that carry out slightly more complicated instructions. Assembly language is directly and easily translatable into machine language, using an assembler
180
5- 180 Machine Layer Software (II) Nowadays, there is less of a distinction between machine language and assembly language Computers are built that have “built-in” translators Microcode—a machine language program built into the CPU—is run when an assembly language command is given. So the assembly language is the machine language!
181
5- 181 The Layers of Computing Underlying hardware CPUMemoryHard diskKeyboard Machine Layer Software Assembly Languages Machine Languages Micro- Programs System Layer Software UNIXWindowsApple System Application Layer Software CompilerGamesUtilitiesBrowser
182
5- 182 System Layer Software The machine layer software is very low level—we need a second layer of software to take care of details The operating system is a constantly running program that: keeps track of computer resources seems to be controlling the computer
183
5- 183 System Layer Software — the Operating System The operating system: “Listens” to keyboard and mouse for input “Talks” to screen and printer Interprets commands as they are input Makes programs available to the user and lets him install new ones Stores information in files, and manages them Controls access to the computer Splits CPU’s attention between several jobs Communicating with other computers
184
5- 184 Lots of Operating Systems But there are three most popular ones today: UNIX (and its Linux variant) Windows (‘98, NT, XP) Apple Macintosh OS X (built on top of Unix) They differ in big and small ways— timesharing, graphical interface, power… Also, embedded systems and handhelds
185
5- 185 What’s the Connection? Question: What’s the relationship between an operating system and hardware? Answer: Not much, even though each operating system has a “most common” implementation on particular hardware: Windows on 80x86 chips, but Windows NT on others Macintosh on 680x0 chips and PowerPC chips UNIX on SPARC chips, but also on 80x86 chips and 680x0 chips…and others
186
5- 186 My Favorite Unix Quotes “Unix is an operating system for people who wish that they, themselves, were computers.” – Ralph Gorin “Contrary to popular belief, Unix is user friendly. It just happens to be selective about who it makes friends with.” – Dave Parnas
187
5- 187 What’s a GUI? A Graphical User Interface is commonplace in computing these days The Apple Macintosh has it, machines with Microsoft Windows have it, the Xerox Star had it, Unix machines have it (in many flavors) A graphical interface contrasts with a character-based interface, such as MS-DOS or plain Unix gives you
188
5- 188 Graphical User Interface The GUI runs on top of the Operating System, and makes the Operating System easier to use Usually includes: bitmapped displays, menus, windows, use of a pointing device (like a mouse), buttons, etc.
189
5- 189 Windows XP
190
5- 190 The Layers of Computing Underlying hardware CPUMemoryHard diskKeyboard Machine Layer Software Assembly Languages Machine Languages Micro- Programs System Layer Software UNIXWindowsApple System Application Layer Software CompilerGamesUtilitiesBrowser
191
5- 191 Application Layer Software These are the programs that do specific jobs—word processors, drawing programs, spreadsheet, tax programs, etc. Applications are written in any convenient language— Pascal, C, Lisp, Modula-2, Ada, Fortran… The underlying platform is usually a specific operating system Applications Programming Language Operating System
192
5- 192 Computer Programming The history of computer programming is a steady move away from machine- oriented views of programming towards concepts and metaphors that more closely reflect the way in which we ourselves understand the world
193
5- 193 Programming progression… Programming has progressed through: machine code assembly language machine-independent programming languages procedures & functions objects
194
5- 194 Programming Languages Low level (first or second generation languages) are closely tied to the computer’s instruction set. They are good when: the program must control some hardware that can only be controlled in this low-level language the program must run extremely quickly
195
5- 195 Machine language – Mark I
196
5- 196 Machine Language 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
197
5- 197 Assembly Language – PDP-11
198
5- 198 Assembly Language – Macro-11 GCD:TSTB BEQSIMPLE MOVA, R5 SXTR4 DIVB, R4 MOVB, A MOV R5, B CALLGCD SIMPLE:RETURN
199
5- 199 Assembly Language – Macro-11 GCD:TSTB BEQSIMPLE MOVA, R5 SXTR4 DIVB, R4 MOVB, A MOV R5, B CALLGCD SIMPLE:RETURN 20/20
200
5- 200 A Computer Command in Machine Language data movement address movement integer arithmetic floating arithmetic binary coded decimal advanced math data conversion logical shift and rotate bit manipulation character and string table operations high level language support program control condition codes input/output MIX devices system control coprocessor and multiprocessor trap generating
201
5- 201 Higher-level Languages Higher level languages (third generation languages) like Pascal, C, C++, Java, etc. are more disconnected from the hardware on which they run They can be used to solve any kind of problem They can run on any kind of computer
202
5- 202 Machine-Independent Programming Languages – Fortran ! This example program solves for roots of the quadratic equation, ! ax^2 +bx +c =0,for given values of a, b and c. ! PROGRAM bisection IMPLICIT NONE INTEGER :: iteration DOUBLE PRECISION :: CC, Er, xl, x0, x0_old, xr ! Set convergence criterion and guess for xl, xr. CC = 1.d-4 xl = 8.d-1 xr = 11.d-1 ! Bisection method. Er =CC +1 iteration = 0 DO WHILE (Er > CC) iteration = iteration + 1 ! Compute x0 and the error. x0_old = x0 x0 = (xl + xr) / 2.d0 Er = DABS((x0 - x0_old)/x0)*100.d0 WRITE (*,10) iteration, x0_old, x0, Er 10 FORMAT (1X,I4,3(2X,E10.4)) this is partial…
203
5- 203 Procedures & Functions – Pascal program ValueArg(output); {Shows how to arrange for a procedure to have arguments.} procedure PrintInitials(First, Last : char); {Within this procedure, the names First and Last represent the argument values. We’ll call write to print them.} begin write(‘My initials are: ’); write(First); writeln(Last) end; {PrintInitials} begin PrintInitials (‘D’, ‘C’); {Any two characters can be arguments.} PrintInitials (‘Q’, ‘T’); {Like strings, characters are quoted.} PrintInitials (‘&’, ‘#’) end. {ValueArg}
204
5- 204 Java Designed by Sun team led by James Gosling Originally called Oak, it was intended for consumer devices like TV-top boxes Being cross platform, and more stable than C++, were essential goals When the TV-top market didn’t materialize, figured they’d try the internet
205
5- 205 Object Oriented Programming (This example from Java) class Time { private int hour, minute; public Time (int h, int m) { hour = h; minute = m; } public void addMinutes (int m) { int totalMinutes = ((60*hour) + minute + m) % (24*60); if (totalMinutes<0) totalMinutes = totalMinutes + (24*60); hour = totalMinutes / 60; minute = totalMinutes % 60; } } this is partial…
206
5- 206 “Intrinsic Power” vs. “Effective Power” This progression is not a matter of “intrinsic power” Anything you can do with a minimally capable computer language, you can theoretically do with any other minimally capable computer language But that is like saying a shovel is theoretically as capable as a tractor. In practice, using a shovel might make things very hard…
207
5- 207 Fourth Generation Languages Application languages (fourth generation) are more high level languages, but also more specialized Examples are PostScript, database languages, etc. They are very good at the tasks they do, and clumsy for general-purpose tasks
208
5- 208 Some PostScript Code %!PS-Adobe-3.0 EPSF-2.0 %Creator: Windows PSCRIPT %Title: PowerPoint - UNIT5.PPT %BoundingBox: 13 10 577 832 %DocumentNeededResources: (atend) %DocumentSuppliedResources: (atend) %Pages: 0 %BeginResource: procset Win35Dict 3 1 /Win35Dict 290 dict def Win35Dict begin/bd{bind def}bind def/in{72 mul}bd/ed{exch def}bd/ld{load def}bd/tr/translate ld/gs/gsave ld/gr /grestore ld/M/moveto ld/L/lineto ld/rmt/rmoveto ld/rlt/rlineto ld /rct/rcurveto ld/st/stroke ld/n/newpath ld/sm/setmatrix ld/cm/currentmatrix ld/cp/closepath ld/ARC/arcn ld/TR{65536 div}bd/lj/setlinejoin ld/lc /setlinecap ld/ml/setmiterlimit ld/sl/setlinewidth ld/scignore false def/sc{scignore{pop pop pop}{0 index 2 index eq 2 index 4 index eq and{pop pop 255 div setgray}{3{255 div 3 1 roll}repeat setrgbcolor}ifelse}ifelse}bd /FC{bR bG bB sc}bd/fC{/bB ed/bG ed/bR ed}bd/HC{hR hG hB sc}bd/hC{
209
5- 209 The Field of Computer Science We’ve been looking at computers (software and hardware), but that’s not an accurate description of the field of Computer Science: HardwareSoftwareTheory
210
5- 210 Areas in Computer Science Algorithms and Data Structures Programming Languages Computer Architecture Operating Systems Software Engineering Symbolic and numerical computation and modeling, graphics Databases Artificial Intelligence Robotics Computer Vision
211
5- 211 How they fit together ArchitectureLanguages Software Engineering Algorithms Operating Systems Robotics Databases Artificial Intelligence Symbolic/Numerical Computation
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.