Programming and Problem Solving With Java Introduction What
Programming and Problem Solving With Java Introduction What is a Computer? Programming a Computer Types of Computer Systems History of Computers The Software Crisis Programming Languages Programming and Problem Solving with Java Copyright 1999, James M. Slack
What is a Computer? ²Computer is a machine Has parts Runs on electricity Breaks down sometimes ²What makes it different from other machines? Can follow a list of instructions Instructions process symbols Therefore Programming and Problem Solving with Java A computer is an information-processing machine 2
What is a Computer? ²Computer follows a list of instructions one instruction at a time Start with first instruction Do each next instruction in turn Stop when last instruction reached ²Similar to how you follow a list of instructions. . . Programming and Problem Solving with Java 3
What is a Computer? ²Example of following instructions - assemble a bike Right Pedal 1. Find the pedal with an "R" marked on the end of the threads. 2. Insert the threads into the opening on the crank on the right side of the bicycle. 3. Twist the threads into the crank by hand in a clockwise direction. 4. Tighten the threads securely with a 5/8 -inch open-end wrench. Left Pedal Follow the same assembly instructions for the right pedal (above) but twist the threads in a counterclockwise direction. Programming and Problem Solving with Java 4
What is a Computer? ²Kinds of instructions a computer can follow (in one step) “Add the numbers 16 and 23” ²Kinds of instructions a computer can’t follow (in one step) “Balance my checkbook” ²What’s the difference? Computer instructions are simple (add 2 numbers, subtract one number from another) Must combine thousands of computer instructions in a program to do more complex tasks Programming and Problem Solving with Java 5
What is a Computer? ²Kinds of computer instructions Arithmetic: add, subtract, multiply, divide Comparison: compare two numbers to see which is greater, or whether the two numbers are equal or not Branching: jump to some other instruction in the program (list of instructions) and continue processing from there ²A computer can execute millions of these simple instructions each second Programming and Problem Solving with Java 6
What is a Computer? ²Major parts of a computer Programming and Problem Solving with Java 7
What is a Computer? ²A vending machine is like a computer Programming and Problem Solving with Java 8
What is a Computer? ²Common input and output devices Programming and Problem Solving with Java 9
What is a Computer? ²Central Processing Unit (CPU) Most important part of the computer Follows instructions ²Important characteristics Clock speed • How fast the computer switches between 2 on states or 2 off states • Early 80’s: 5, 000 times per second (5 MHz) • Today: 400, 000 to 1, 000, 000 and up! (400 MHz to 1 GHz) Instruction set • The set of machine language instructions the CPU understands • Examples: Intel Pentium, Motorola Power. PC, IBM AS/400 • Some CPUs understand machine language instructions of others -- AMD and Cyrix chips understand Intel Pentium instructions Programming and Problem Solving with Java 10
What is a Computer? ²Subcomponents of a CPU The arithmetic/logic unit, or ALU: does addition, subtraction, and other arithmetic operations, and also compares values The control unit. determines which instruction to execute next A small number of registers. each is a high-speed storage area for temporary results Programming and Problem Solving with Java 11
What is a Computer? ²Types of Computer Memory Primary Secondary ²Primary Memory Connected directly to the CPU Usually called RAM (random-access memory) Usually loses contents when power switched off -- volatile Programming and Problem Solving with Java 12
What is a Computer? ²Secondary Memory Disks, tapes, floppy disks Is sometimes removable Much cheaper than primary memory Slower than primary memory Keeps contents when power switched off -- non-volatile Programming and Problem Solving with Java 13
What is a Computer? ²Types of Computer Memory Programming and Problem Solving with Java 14
What is a Computer? ²Primary Memory Can imagine as sequence of cells Each cell has a memory address First cell is memory address 0 Programming and Problem Solving with Java 15
What is a Computer? ²Primary Memory Each memory cell stores a single value, such as a small number If you put a new value into a memory cell, the old contents is lost Programming and Problem Solving with Java 16
What is a Computer? ²Primary Memory Can retrieve the contents of a cell without losing the contents Programming and Problem Solving with Java 17
What is a Computer? ² Secondary Memory Information clustered in files File: collection of related information Each file has a name Example: NAMES. DAT, Balance. java Programming and Problem Solving with Java 18
Programming a Computer ²How we solve most problems without a computer Analyze the problem, come up with a solution Programming and Problem Solving with Java 19
Programming a Computer ² How we can get the computer to solve a problem Must come up with an algorithm (series of steps) Computer follows the steps to solve the problem Programming and Problem Solving with Java 20
Programming a Computer ²Algorithm Steps that a computer can follow to solve a problem Holiday Cookies 1 cup sugar 3/4 cup shortening 1 cup dark corn syrup 2 eggs 1 lemon rind (grated) 3 cups flour 1 tsp. baking powder 1 tsp. baking soda 1/4 tsp. ginger Similar to 1 tsp. cinnamon 1/2 tsp. nutmeg a recipe 1/2 tsp. cloves 2 tsp. anise seed 3/4 tsp. ground cardaman icing (powder sugar and water) colored sugar and candy decorations 1. Sift dry ingredients together in a large bowl and set aside. 2. In another large bowl, use mixer to cream sugar and shortening together. 3. Mix syrup, eggs, and lemon rind into sugar and shortening mixture. 4. Add dry ingredients to mixture gradually. 5. Refrigerate at least one hour to make handling easier. 6. With rolling pin, roll out to 1/8 -inch thickness on a floured surface, and cut with cookie cutters. 7. Bake on greased cookie sheet 10 -12 minutes at 375°F. 8. Remove from cookie sheet and let cool to room temperature. 9. Frost with icing, and decorate with colored sugar and candy. Programming and Problem Solving with Java 21
Programming a Computer ²Recipe lists steps, but doesn’t say who is doing the steps Implied that you (the cook) should do the steps Many algorithms written this way -- structured approach to programming ²New approach -- object-oriented programming Consists of a set of cooperating objects trying to accomplish a goal Each step says who (which object) should do that step Similar to the script for a play Programming and Problem Solving with Java 22
Programming a Computer THE IMPORTANCE OF BEING EARNEST by Oscar Wilde The Persons of the Play John Worthing, J. P. Algernon Moncrieff Rev. Canon Chasuble, D. D. Merriman, Butler Lane, Manservant Lady Bracknell Hon. Gwendolen Fairfax Cecily Cardew Miss Prism, Governess The Scenes of the Play Act I: Algernon Moncrieff's Flat in Half-Moon Street, W. Act II: The Garden at the Manor House, Woolton. Act III: Drawing-Room at the Manor House, Woolton Programming and Problem Solving with Java 23
Programming a Computer THE IMPORTANCE OF BEING EARNEST (continued) ACT ONE SCENE. Morning-room in Algernon's flat in Half-Moon Street. The room is luxuriously and artistically furnished. The sound of a piano is heard in the adjoining room. (Lane is arranging afternoon tea on the table, and after the music has ceased, Algernon enters. ) ALGERNON. Did you hear what I was playing, Lane? LANE. I didn't think it polite to listen, sir. ALGERNON. I'm sorry for that, for your sake. I don't play accurately-anyone can play accurately-but I play with wonderful expression. As far as the piano is concerned, sentiment is my forte. I keep science for life. LANE. Yes, sir. ALGERNON. And, speaking of the science of life, have you got the cucumber sandwiches cut for Lady Bracknell? LANE. Yes, sir. (Hands them on a salver. ) ALGERNON. (Inspects them, takes two, and sits down on the sofa. ) Oh!. . . by the way, Lane, I see from your book that on Thursday night, when Lord Shoreman and Mr. Worthing were dining with me, eight bottles of champagne are entered as having been consumed. LANE. Yes, sir; eight bottles and a pint. ALGERNON. Why is it that at a bachelor's establishment the servants invariably drink the champagne? I ask merely for information. Programming and Problem Solving with Java 24
Programming a Computer THE IMPORTANCE OF BEING EARNEST (continued) LANE. I attribute it to the superior quality of the wine, sir. I have often observed that in married households the champagne is rarely of a first-rate brand. ALGERNON. Good Heavens! Is marriage so demoralizing as that? LANE. I believe it is a very unpleasant state, sir. I have had very little experience of it myself up to the present. I have only been married once. That was in consequence of a misunderstanding between myself and a young person. ALGERNON. (Languidly. ) I don't know that I am much interested in your family life, Lane. LANE. No, sir; it is not a very interesting subject. I never think of it myself. ALGERNON. Very natural, I am sure. That will do, Lane, thank you. LANE. Thank you, sir. (Lane goes out. ) ALGERNON. Lane's views on marriage seem somewhat lax. Really, if the lower orders don't set us a good example, what on earth is the use of them? They seem, as a class, to have absolutely no sense of moral responsibility. (Enter Lane. ) LANE. Mr. Ernest Worthing. (Enter Jack. Lane goes out. ). . . Programming and Problem Solving with Java 25
Programming a Computer ²Why is an object-oriented algorithm like a script? Object-oriented algorithm simulates activities of several explicit actors Each actor has specific steps to perform Each actor free to use any appropriate technique to accomplish its task Combined effort of all these simulated actors results in the goal of the algorithm Combined effort of real actors of a play results in enjoyable entertainment Programming and Problem Solving with Java 26
Programming a Computer ²Programming languages Very formal language with strict rules about spelling and grammar Need write algorithm in a programming language before running the algorithm on the computer ²Many programming languages Will use Java in this course Programming and Problem Solving with Java 27
Programming a Computer ²Computers understand machine language directly Example: add 16 and 23 in Intel 8086 machine language 1011 0000 0100 0001 0111 1010 0100 1000 0000 Programming and Problem Solving with Java 28
Programming a Computer ²Parts of machine language program step First statement from example 1011 0000 0001 0000 Copy information to a register Use the AL register The number 16 in binary (base 2) Instruction says: Copy the number 16 into the AL register ²Difficult to read and write machine language! Programming and Problem Solving with Java 29
Programming a Computer ²Assembly language One step up from machine language Each assembly language instruction corresponds to one machine language instruction MOV AL, 16 D 1011 0000 0001 0000 ADD AL, 23 D 0000 0100 0001 0111 MOV [SUM], AL 1010 0100 1000 0000 Programming and Problem Solving with Java 30
Programming a Computer ²Assembly language Computer can’t understand assembly language directly Must translate from assembly to machine language Assembler: program that does this translation Programming and Problem Solving with Java 31
Programming a Computer ²High-level languages Each high-level language instruction may correspond to several machine language instructions Easier for people to read and write than assembly Java example: 1011 0000 0001 0000 sum = 16 + 23; 0000 0100 0001 0111 1010 0100 1000 0000 (Note: Java usually translated to Java bytecodes, not Intel machine language. . . ) Programming and Problem Solving with Java 32
Programming a Computer ²High-level languages Must translate high-level language program to machine language before computer can execute it Compiler: program that does this translation Programming and Problem Solving with Java 33
Programming a Computer: Java ²The Java Programming Language A high-level language Java compiler translates to Java bytecodes for execution on a Java Virtual Machine (JVM) Programming and Problem Solving with Java 34
Programming a Computer: Java ²Advantage of Java Virtual Machine approach Can run compiled Java program on any machine with a Java Virtual Machine installed Makes compiled Java programs very portable ²Disadvantage Takes more time -- Java programs run slower than programs compiled to machine code ²BUT. . . Today’s machines are so fast that the difference is noticeable for many programs Programming and Problem Solving with Java 35
Programming a Computer: Java ²Kinds of Java programs Applications Applets ²Applications Run as stand-alone programs Programs stored on the same machine they run on Like a text editor, word processor, spreadsheet, . . . Can be graphical or console-based ²Applets Run inside a web browser Programs stored on a web server, run on a client machine Programming and Problem Solving with Java 36
Programming a Computer: Java ²Example Java program (application) // This Java program finds the sum of 16 and 23, // then displays the result. public class Add 16 And 23 { public static void main(String[] args) { int sum; } } sum = 16 + 23; System. out. println("The sum of 16 and 23 is " + sum); ²Steps to run this program Type the program text exactly Save the program in file Add 16 And 23. java Compile the program with a Java compiler Run program Add 16 And 23. class with a JVM interpreter Programming and Problem Solving with Java 37
Programming a Computer: Java ²Use an editor that saves text files, such as MS-DOS edit (in MS-DOS box) Programming and Problem Solving with Java 38
Programming a Computer: Java ²Compile the program javac Add 16 And 23. java ²Run the program java Add 16 And 23 Result: program should display The sum of 16 and 23 is 39 $ javac Add 16 And 23. java $ java Add 16 And 23 The sum of 16 and 23 is 39 $ Unix display Programming and Problem Solving with Java 39
Programming: Development ²Example program: display average of series ²First step: understand the problem Where should program get the numbers? Keyboard How does program know how many numbers? Will enter 0 at end of list Where should program display result? On screen ²Second step: come up with algorithm Solve problem yourself -- write down steps you took Result is an algorithm Programming and Problem Solving with Java 40
Programming: Development ²Steps for finding average of series of numbers Programming and Problem Solving with Java 41
Programming: Development ²Convert steps into an algorithm Display the program's title Set running total to 0. Set running count to 0. Repeat these steps: • Read a value. • Check if value is 0 (stop this loop if so). • Add value to running total. • Add 1 to running count. Compute the average by dividing the running total by the count. Display the average. Programming and Problem Solving with Java 42
Programming: Development ²Convert algorithm into program // This program displays the average of a series of // numbers terminated by zero. The user enters the numbers using // the keyboard, and the average is displayed on the screen. import java. io. *; import java. text. Number. Format; public class Compute. Average { public static void main(String[] args) throws java. io. IOException, java. text. Parse. Exception { double input. Value; // Last value read from the user double running. Total; // Total of all input values read so far int running. Count; // Count of all input values read so far double average; // Average of input values // Create an input stream and attach it to the standard // input stream Buffered. Reader in. Stream = new Buffered. Reader(new Input. Stream. Reader(System. in)); // Create a number formatter object Number. Format formatter = Number. Format. get. Instance(); // Display the program title System. out. println("--- Compute Average ---"); // Set running total to 0 running. Total = 0; Programming and Problem Solving with Java 43
Programming: Development // Set running count to 0 running. Count = 0; // Read the first input value System. out. print("Enter a value (0 to stop): "); System. out. flush(); input. Value = formatter. parse(in. Stream. read. Line()). double. Value(); // Keep reading until 0 while (input. Value != 0) { // Add value to running total running. Total = running. Total + input. Value; // Add 1 to running count running. Count = running. Count + 1; } // Read the next input value System. out. print("Enter a value (0 to stop): "); System. out. flush(); input. Value = formatter. parse(in. Stream. read. Line()). double. Value(); // Compute the average = running. Total / running. Count; } } // Display the average System. out. println("The average is " + average); Programming and Problem Solving with Java 44
Programming: Development ²Last step: Make sure the program works correctly First test -- ok --- Compute Average --Enter a value (0 to stop): The average is 6. 73333 9 3. 2 8 0 --- Compute Average --Enter a value (0 to stop): Enter a value (0 to stop): The average is 5. 79429 9. 1 2. 6 7. 3 1. 4 6. 44 8 5. 72 0 Second test -- ok Third test -- not ok (doesn’t work if nothing to average) --- Compute Average --Enter a value (0 to stop): 0 The average is Na. N Programming and Problem Solving with Java 45
Programming: Development ²Modified program // This program displays the average of a series of // numbers terminated by zero. The user enters the numbers using // the keyboard, and the average is displayed on the screen. import java. io. *; import java. text. Number. Format; public class Compute. Average { public static void main(String[] args) throws java. io. IOException, java. text. Parse. Exception { double input. Value; // Last value read from the user double running. Total; // Total of all input values read so far int running. Count; // Count of all input values read so far double average; // Average of input values // Create an input stream and attach it to the standard // input stream Buffered. Reader in. Stream = new Buffered. Reader(new Input. Stream. Reader(System. in)); // Create a number formatter object Number. Format formatter = Number. Format. get. Instance(); // Display the program title System. out. println("--- Compute Average ---"); // Set running total to 0 running. Total = 0; Programming and Problem Solving with Java 46
Programming: Development // Set running count to 0 running. Count = 0; // Read the first input value System. out. print("Enter a value (0 to stop): "); System. out. flush(); input. Value = formatter. parse(in. Stream. read. Line()). double. Value(); // Keep reading until 0 while (input. Value != 0) { // Add value to running total running. Total = running. Total + input. Value; // Add 1 to running count running. Count = running. Count + 1; } if (running. Count > 0) { // Compute the average = running. Total / running. Count; Changes } // Read the next input value System. out. print("Enter a value (0 to stop): "); System. out. flush(); input. Value = formatter. parse(in. Stream. read. Line()). double. Value(); // Display the average System. out. println("The average is " + average); } } else System. out. println("Can't compute average: No input values"); Programming and Problem Solving with Java 47
Programming: Development ²Last step: Test program again First test -- ok --- Compute Average --Enter a value (0 to stop): The average is 6. 73333 9 3. 2 8 0 --- Compute Average --Enter a value (0 to stop): Enter a value (0 to stop): The average is 5. 79429 9. 1 2. 6 7. 3 1. 4 6. 44 8 5. 72 0 Second test -- ok Third test -- ok --- Compute Average --Enter a value (0 to stop): 0 Can't compute average: No input values Programming and Problem Solving with Java 48
Programming: Development ²Steps in program development Understand the problem Come up with an algorithm Write the program Test the program Programming and Problem Solving with Java 49
Programming: Development ²Understand the problem Need to understand problem thoroughly before beginning to write program Tempting to start writing program before understanding problem -- probably single most common cause of errors in programs ²How to understand the problem Look at input and output requirements Ask people involved with the problem domain Try writing about the program -- write what it should do in your own words Programming and Problem Solving with Java 50
Programming: Development ²Come up with an algorithm ²Algorithm is a series of steps, and it. . . is finite -- can’t have infinite series of steps is unambiguous-- must state precisely what to do at each step is effective -- must do what it is supposed to to will terminate -- won’t go on forever Programming and Problem Solving with Java 51
Programming: Development ²Write the program If you have an algorithm this step is mechanical Gets easier the more you learn and use Java ²Desk checking Simulate the action of the computer in your mind Good time to do this is as you write the program (you’re thinking about the program anyway) Programming and Problem Solving with Java 52
Programming: Development ²Test the program Try the program with sample data Make sure to try several different samples (may work on one set but not others) Don’t worry if it doesn’t work the first time -- professionals rarely get it right the first time, either Programming and Problem Solving with Java 53
Types of Computers ²Four major types of computer systems Single-user personal computer Time-sharing computer Batch computer Network computer system Programming and Problem Solving with Java 54
Types of Computers ²Single-user personal computer One person uses at a time Has become popular since early 80’s Interactive -- computer responds immediately to user commands Programming and Problem Solving with Java 55
Types of Computers ²Time-sharing computer Many people can use simultaneously Each person uses a terminal connected to the computer Programming and Problem Solving with Java 56
Types of Computers ²How does time-sharing computer service many people simultaneously? Only appears to act this way Actually does a little bit of work for each person in turn Process is called polling Polls so fast that it seems like the computer is serving everyone at the same time Programming and Problem Solving with Java 57
Types of Computers ²Batch computer system Not interactive -- must schedule work with computer operator Operator schedules work so the computer can get the most work done in the shortest time ²Advantage of batch: efficiency ²Used in large companies for repetitive tasks Payroll, accounting, . . . Programming and Problem Solving with Java 58
Types of Computers ²Computer network Group of connected computers Server: fast, expensive computer that stores programs and other files for the other computers (clients) ²Advantage of network vs. time-sharing Each client is a computer Response time is better Programming and Problem Solving with Java 59
History of Computers ²Abacus: oldest mechanical calculating aid Invented in Babylon about 3000 years ago Also used by Chinese Each wire represents a decimal position (ones, tens, . . . ) Can do addition, subtraction, multiplication and division by moving beads on the strings Programming and Problem Solving with Java 60
History of Computers ²Blaise Pascal Invented first mechanical calculator in 1642 Did multiplication and division ²Gottfried von Leibnitz Expanded Pascal's machine in 1671 Handled multiplication, division, and square roots ²Joseph-Marie Jacquard Invented loom that read tape of punched cards in 1801 Wove cloth according to instructions on cards First machine that could be reprogrammed Programming and Problem Solving with Java 61
History of Computers ²Charles Babbage Designed Difference Engine (mid 1800’s) Supposed to compute and print mathematical tables Never completed -- Babbage spent time designing Analytical Engine Designed to follow instructions in a program and thus handle any computation Would store program on cards in the machine's memory - this is the stored program concept Never completed -- English government stopped the funding Probably wouldn’t have worked -- required metalworking skills beyond what was possible at the time Programming and Problem Solving with Java 62
History of Computers ²Augusta Ada (later Countess of Lovelace) World’s first computer programmer Assisted Babbage Translated one of Babbage’s papers on Analytical Engine from French to English (1842) In margins, she wrote examples of how to use the machine -- program examples Programming and Problem Solving with Java 63
History of Computers ²Herman Hollerith Invented method of using punched cards for automated data processing US government used Hollerith's machines to tabulate the 1890 census Hollerith's firm later merged with three other firms to become International Business Machines (IBM) Punched cards used for tabulating and sorting information into the 1960's Programming and Problem Solving with Java 64
History of Computers ²Howard Aiken Designed the Mark I computer -- the world's first automatic computer (1944) Operated with electro-mechanical switches Able to multiply two numbers together in six seconds ²John W. Mauchly and J. Presper Eckert Designed ENIAC -- the first general-purpose electronic computer (1946) Hundreds of times faster than any electro-mechanical computing device Programmed by plugging wires into holes along the outside of the machine. Programming and Problem Solving with Java 65
History of Computers ²First generation computers (1950’s) UNIVAC I (1951, Sperry-Rand): first commercial computer Other companies soon followed Computers were bulky, unreliable Used vacuum tubes for electronic switching (hot -burned out often) Most programs written in machine language Used punched cards for data storage Programming and Problem Solving with Java 66
History of Computers ²Second generation computers (late 50’s mid 60’s) Started using transistors instead of vacuum tubes Computers became more reliable First high-level languages (FORTRAN, COBOL, Algol) Larger primary memory Magnetic tapes used for long-term data storage Programming and Problem Solving with Java 67
History of Computers ²Third generation computers (mid 60’s to early 70’s) IBM introduced System 360 line: every machine in the line could run the same programs Integrated circuits used: contains many transistors Most computers ran in batch mode Programming and Problem Solving with Java 68
History of Computers ²Fourth generation computers (early 70’s on) Very large scale integration: hundreds, thousands, or millions of transistors on a single chip Computers have become inexpensive and reliable Time-sharing popular in 1970’s and 1980’s Today, single-user personal computers are popular The Internet connects many computers in a world-wide computer network Programming and Problem Solving with Java 69
Software Crisis ²Hardware vs. software Hardware: physical parts of the computer Software: computer programs ²Advances in hardware have been spectacular Fast, affordable computer systems Computers in everyday appliances ²Advances in software Have been many significant advances (high-level languages, compilers, object-oriented programming, modern design techniques, . . . ) Still need to do more though. . . Programming and Problem Solving with Java 70
Software Crisis ²Today, many programs are Expensive: they cost much more than initial projections Unreliable: they have serious errors which cause them to work incorrectly Late: they are delivered months or years after they're promised ²This is a crisis. . . Programming and Problem Solving with Java 71
Software Crisis ²Abstraction Ignore details, concentrate on essential features Most powerful tool to solve the software crisis ²Levels of abstraction Sometimes, details at one level become essential features at another level Example: stereo • Consumer level: concentrate on tuner, CD player, tape desk, speakers, amplifier • Stereo designer: concentrate on circuits, discrete parts, chips • Chip designer: concentrate on circuits within the chip Programming and Problem Solving with Java 72
Software Crisis ²Use abstraction when writing computer program Programmer gives a name to each part of the program When working within the part, programmer concentrates on the steps within that part When working outside the part, programmer thinks of the part by its name (ignores the steps within) ²Usually several levels of abstraction in a computer program Method: most detailed level Class: consists of several methods (and other things. . . ) Package: consists of several classes System of packages: consists of several packages Programming and Problem Solving with Java 73
Programming Languages ²Hundreds of high-level programming languages No best programming language for all uses Some are better than others for certain uses ²Four major groups Procedural Functional Logic Object-oriented Programming and Problem Solving with Java 74
Languages: Procedural ²Procedural languages Largest group of languages Also called imperative languages Program consists of list of statements ²Variables Program stores temporary values in variables, and can change the value of a variable Different from mathematics: once we have chosen the value of a variable, it remains fixed throughout the expression Programming and Problem Solving with Java 75
Languages: Procedural ²BASIC (Beginner’s All-purpose Symbolic Instruction Code) Popular language for beginners Simple syntax (originally only 14 statement types) Can run on small computers Example 10 20 30 40 50 REM THIS BASIC REM 16 AND 23, LET SUM = 16 + PRINT "The sum END PROGRAM FINDS THE SUM OF THEN DISPLAYS THE RESULT. 23 of 16 and 23 is ", SUM ²Microsoft Visual BASIC Much more sophisticated version of BASIC Full-fledged development system for Microsoft Windows Programming and Problem Solving with Java 76
Languages: Procedural ²COBOL (COmmon Business Oriented Language) Most commonly used language in business Designed for ease of data movement Example IDENTIFICATION DIVISION. PROGRAM-ID. ADDNUMS. AUTHOR. SLACK. DATE-WRITTEN. JUL 11, 1997. DATE-COMPILED. JUL 12, 1997. * THIS COBOL PROGRAM FINDS THE SUM * OF 16 AND 23, THEN DISPLAYS THE RESULT. ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. IBM-370. OBJECT-COMPUTER. IBM-370. DATA DIVISION. WORKING-STORAGE SECTION. 77 TOTAL PICTURE 99. PROCEDURE DIVISION. ADD 16, 23 GIVING TOTAL. DISPLAY 'THE SUM OF 16 AND 23 IS ', TOTAL UPON CONSOLE. STOP RUN. END PROGRAM Programming and Problem Solving with Java 77
Languages: Procedural ²FORTRAN (FORmula TRANslator) The first high-level language Popular with scientists and engineers (although many engineers are switching to C and C++ today) Example C C PROGRAM ADDNUMS THIS FORTRAN PROGRAM FINDS THE SUM OF 16 AND 23, THEN DISPLAYS THE RESULT. INTEGER SUM = 16 + 23 WRITE (*, 10) SUM 10 FORMAT ('THE SUM OF 16 AND 23 IS ', I 2) STOP END Programming and Problem Solving with Java 78
Languages: Procedural ²C Popular with programmers who write system-level code (operating systems, compilers, . . . ) Example /* This C program finds the sum of 16 and 23, then displays the result. */ #include <stdio. h> void main(void) { int sum; sum = 16 + 23; printf("The sum of 16 and 23 is %dn", sum); } Programming and Problem Solving with Java 79
Languages: Procedural ²Pascal (named after Blaise Pascal) Designed as a simple alternative to Algol (another early programming language) Used extensively to teach programming until the early 1990’s Example PROGRAM Add. Nums (Input, Output); { This Pascal program finds the sum of 16 and 23, then displays the result. } VAR Sum : Integer; BEGIN Sum : = 16 + 23; write. Ln ('The sum of 16 and 23 is ', Sum) END. Programming and Problem Solving with Java 80
Languages: Functional ²Functional languages Based on mathematical functions Program consists of functions and function calls No variables in a pure functional language ²Lisp Most popular functional language Used widely in artificial intelligence (especially in the US) Example ; This Lisp program finds the ; sum of 23 and 16, then displays the result. (progn (let (Sum) (setq Sum (+ 23 16)) (princ "The sum of 23 and 16 is ") (princ Sum) ) ) Programming and Problem Solving with Java 81
Languages: Logic ²Logic languages Based on formal rules of logic and inference Once set, program can't change value of a variable Program consists of a set of known facts, plus rules for inferring new facts from the existing facts Programming and Problem Solving with Java 82
Languages: Logic ²Prolog Most popular logic language Used widely in artificial intelligence (especially in Europe and Japan) Example /* This Prolog program finds the sum of 16 and 23, then displays the result. */ run : - Sum is 16 + 23, write ("The sum of 16 and 23 is ", Sum), nl. Programming and Problem Solving with Java 83
Languages: Logic ²Another example of Prolog /* Shows Prolog's inference ability */ likes(tom, pizza). likes(tom, apple). likes(jill, taco). likes(jill, apple). likes(bob, beans). likes(bob, apple). likes(jody, Food) : - likes(jill, Food), likes(bob, Food). Run program by writing a query Example Goal: likes(jill, Food) Food=taco Food=apple 2 Solutions Can also infer solutions based on known facts Goal: likes(jody, Food) Food=apple 1 Solution Programming and Problem Solving with Java 84
Languages: Object-oriented ²Object-oriented languages Model each real-world entity as an object Each object has set of values and behaviors Each object is therefore active, because it has behaviors ²Simula (Simulation language) First object-oriented language (1967) ²Smalltalk First pure object-oriented language (early 1980’s) Everything in the language is an object Programming and Problem Solving with Java 85
Languages: Object-oriented ²C++ Introduced in the mid 1980’s Based on the C language Hybrid language: procedural & object-oriented Example: // This C++ program finds the sum of 16 and 23, // then displays the result. #include <iostream. h> void main(void) { int sum; sum = 16 + 23; cout << "The sum of 16 and 23 is " << sum << endl; } Programming and Problem Solving with Java 86
Languages: Object-oriented ²Java Introduced in 1995 by Sun Microsystems Object-oriented language, but not as pure as Smalltalk • In Java, primitive values (numbers, characters) are not objects -- they are values • In Smalltalk, everything is an object During its research, was designed for use in appliances Released version designed for use on the Internet and as a general-purpose programming language Probably the most famous programming language of all time • Lots of coverage in regular news, unlike other programming languages • Huge excitement about the language Programming and Problem Solving with Java 87
- Slides: 87