2. Basic Programming Concepts
Total Page:16
File Type:pdf, Size:1020Kb
COMPUTER SCIENCE COMPUTER SCIENCE SEDGEWICK/WAYNE SEDGEWICK/WAYNE 2. Basic Programming Concepts •Why programming? 2. Basic Programming •Program development Concepts •Built-in data types •Type conversion Sections 1.1 and 1.2 http://introcs.cs.princeton.edu CS.2.A.Basics.Why You need to know how to program Programming: telling a computer what to do in order to be able to tell a computer what you want it to do. Programming Naive ideal: Natural language instructions. • Is not just for experts. • Is a natural, satisfying and creative experience. “Please simulate the motion of N heavenly bodies, subject to Newton’s laws of motion and gravity.” • Enables accomplishments not otherwise possible. • The path to a new world of intellectual endeavor. Prepackaged solutions (apps) are great when what they do is what you want. Challenges • Need to learn what computers can do. • Need to learn a programming language. Telling a computer what to do Programming enables you to make a computer do anything you want. well, almost anything (stay tuned) “ Instead of imagining that our main task is to instruct a first programmer first computer computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. ” − Don Knuth Analytical Ada Lovelace Engine 3 4 Telling a computer what to do Our Choice: Java Machine language Natural language High-level language Java features • Easy for computer. • Easy for human. • Some difficulty for both. • Widely used. • Error-prone for human. • Error-prone for computer. • An acceptable tradeoff. • Widely available. • Continuously under development since early 1990s. Kids Make Nutritious Snacks. for (int t = 0; t < 2000; t++) • Embraces full set of modern abstractions. 10: 8A00 RA ← mem[00] { 11: 8B01 RB ← mem[01] a[0] = (a[11] ^ a[9]); • Variety of automatic checks for mistakes in programs. 12: 1CAB RC ← RA + RB Red Tape Holds Up New Bridge. System.out.print(a[0]); James Gosling 13: 9C02 mem[02] ← RC Police Squad Helps Dog Bite Victim. for (int i = 11; i > 0; i--) 14: 0000 halt a[i] = a[i-1]; } $100 billion, Adding two numbers (see Lecture 10) Local High School Dropouts Cut in Half. Java economy 5 million developers Actual newspaper headlines Simulating an LFSR (see Lecture 1) • Mars rover. —Rich Pattis • Cell phones. But which high-level language? • Blu-ray Disc. • Web servers. • Medical devices. • Supercomputing. • … Naive ideal: A single programming language for all purposes. 5 6 Our Choice: Java A rich subset of the Java language vocabulary Java features built-in operations on String object Math numeric types types operations assignment oriented methods Math • Widely used. methods int + + = static Math.sin() punctuation • Widely available. long - "" class Math.cos() Math.sin()int • Continuously under development since early 1990s. double * length() flow control public Math.log() Math.cos()long System Math.log() • Embraces full set of modern abstractions. char / charAt() if private Math.exp() methods double Math.exp() • Variety of automatic checks for mistakes in programs. String % compareTo() else new Math.pow() System.print() char Math.pow() boolean ++ matches() for final Math.sqrt() System.println() String Math.sqrt() Facts of life “ There are only two kinds of -- while toString() Math.min() System.printf() boolean programming languages: those boolean main() Math.max() Math.min() • No language is perfect. punctuation comparisons operations people always [gripe] about and our Std methods Math.max() • You need to start with some language. { < true arrays Math.abs() StdIn.read*() those nobody uses.” Math.PI Math.abs() } <= false a[] StdOut.print*() Math.PI − Bjarne Stroustrup ( > Our approach ! length type conversion methods StdDraw.*() ) >= && new • Use a minimal subset of Java. Integer.parseInt() StdAudio.*() , == || • Develop general programming skills that are applicable to many languages. Double.parseDouble() StdRandom.*() ; != It’s not about the language! Your programs will primarily consist of these plus identifiers (names) that you make up. 7 8 Anatomy of your first program Anatomy of your next several programs program name program name main() method main() method text file named text file named HelloWorld.java public class HelloWorld MyProgram.java public class MyProgram { { public static void main(String[] args) public static void main(String[] args) { { System.out.println("Hello, World"); ... } } } } body of main() (a single statement) body of main() (a sequence of statements) 9 10 Pop quiz on "your first program" (easy if you did Exercise 1.1.2) Three versions of the same program. Q. Use common sense to cope with the following error messages. public class HelloWorld { public static void main(String[] args) { % javac MyProgram.java System.out.println("Hello, World"); } % java MyProgram } Main method not public. /************************************************************************* * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * Prints "Hello, World". By tradition, this is everyone's first program. * * % java HelloWorld * Hello, World * *************************************************************************/ public class HelloWorld { % javac MyProgram.java public static void main(String[] args) { MyProgram.java:3: invalid method declaration; return type required System.out.println("Hello, World"); } public static main(String[] args) } ^ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } Lesson: Fonts, color, comments, and extra space are not relevant to Java. 11 12 Note on program style COMPUTER SCIENCE SEDGEWICK/WAYNE Different styles are appropriate in different contexts. • DrJava • Booksite • Book • Your code Enforcing consistent style can 2. Basic Programming Concepts • Stifle creativity. • Confuse style with language. •Why programming? •Program development Emphasizing consistent style can • Make it easier to spot errors. •Built-in data types • Make it easier for others to read and use code. •Type conversion • Enable development environment to provide visual cues. Bottom line for this course: Life is easiest if you use DrJava style. 13 CS.2.B.Basics.Develop Program development in Java Software for program development is a three-step process, with feedback Any creative process involves cyclic refinement/development. 1. EDIT your program EDIT COMPOSE • Create it by typing on your computer's keyboard. • Result: a text file such as HelloWorld.java. COMPILE RUN REHEARSE PLAY EDIT 2. COMPILE it to create an executable file • Use the Java compiler A significant difference with programs: We can use our computers to faciliate the process. • Result: a Java bytecode file file such as HelloWorld.class Program development environment: Software for editing, compiling and running programs. • Mistake? Go back to 1. to fix and recompile. COMPILE RUN not a legal Java program 3. RUN your program Two time-tested options: (Stay tuned for details). • Use the Java runtime. • Result: your program’s output. Virtual terminals Integrated development environment • Mistake? Go back to 1. to fix, recompile, and execute • Same for many languages and systems. • Often language- or system-specific. a legal Java program that does the wrong thing • Effective even for beginners. • Can be helpful to beginners. Bottom line: Extremely simple and concise. Bottom line: Variety of useful tools. 15 16 Program development environments: a very short history Program development with switches and lights Historical context is important in computer science. Circa 1970: Use switches to input binary program code and data, lights to read output. • We regularly use old software. • We regularly emulate old hardware. • We depend upon old concepts and designs. PDP-8, circa 1970 lights Widely-used methods for program development • switches and lights 1960 • punched cards/compiler/runtime 1970 • editor/compiler/runtime/terminal • editor/compiler/runtime/virtual terminal 1980 • integrated development environment 1990 switches 2000 Stay tuned for details [lectures on the "TOY machine"]. 17 18 Program development with punched cards and line printers Program development with timesharing terminals Mid 1970s: Use punched cards to input program code and data, line printer for output. Late 1970s: Use terminal for editing program, reading output, and controlling computer. IBM System 360, circa 1975 VAX 11/780 circa 1977 VT-100 terminal Ask your parents about the "computer center" for details. Timesharing allowed many users to share the same computer. 19 20 Program development with personal computers (one approach) Program development with personal computers (another approach) 1980s to present day: Use multiple virtual terminals to interact with computer. 1980s to present day: Use a customized application for program development tasks. • Edit your program using any text editor in a virtual terminal. • Edit your program using the built-in text editor. • Compile it by typing javac HelloWorld.java in another virtual terminal. • Compile it by clicking the “compile” button. • Run it by typing javac HelloWorld.java • Run it by clicking the “run” button or using the pseudo-command line. “Integrated Development Environment” (IDE) virtual terminal for editor virtual terminal to compile, run and examine output http://drjava.org “compile” button invoke Java compiler at command line “run” button invoke Java runtime at command line pseudo-command line virtual TV set 21 22 Software for program development: tradeoffs Lessons from short history Virtual terminals