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 DrJava IDE Every computer has a program development environment that allows us to • EDIT programs. • COMPILE them to create an executable file. Pros Pros • RUN them and examine the output. • Approach works with any language. • Easy-to-use language-specific tools. • Useful beyond programming. • System-independent (in principle). Two approaches that have served for decades and are still effective: • Used by professionals. • Used by professionals. • multiple virtual terminals. • Has withstood the test of time. • Can be helpful to beginners. • integrated development environments.
Cons Cons Macbook Air 2014 • Good enough for long programs? • Overkill for short programs? • Dealing with independent applications. • Big application to learn and maintain. • Working at too low a level? • Often language- or system-specific.
Apple Macintosh 1984 IBM PC 1990s This course: Used in lectures/book. Recommended for assignments. Wintel ultrabooks 2010s Xerox Alto 1978 23 24 COMPUTER SCIENCE Built-in data types SEDGEWICK/WAYNE
A data type is a set of values and a set of operations on those values.
type set of values examples of values examples of operations
'A' char characters compare '@'
2. Basic Programming Concepts "Hello World" String sequences of characters concatenate "CS is fun"
•Why programming? 17 int integers add, subtract, multiply, divide •Program development 12345 3.1415 •Built-in data types double floating-point numbers add, subtract, multiply, divide 6.022e23 •Type conversion true boolean truth values and, or, not false
Java's built-in data types
CS.2.C.Basics.Types 26
Pop quiz on data types Basic Definitions
Q. What is a data type? A variable is a name that refers to a value. A literal is a programming-language representation of a value. A declaration statement associates variables with a type. An assignment statement associates a value with a variable.
variables
declaration statement int a, b; a = 1234; assignment statements b = 99; int c = a + b; combined declaration and assignment statement
literals
27 28 Variables, literals, declarations, and assignments example: exchange values Data type for computing with strings: String
String data type public class Exchange A trace is a table of variable values after each statement. values sequences of characters { Important note: public static void main(String[] args) a b t typical literals "Hello, " "1 " " * " { Character interpretation depends on context! undefined undefined undefined operation concatenate int a = 1234; operator + int b = 99; int a = 1234; 1234 undefined undefined character int t = a; int b = 99; 1234 99 undefined Ex 1: plus signs "1234" + " + " + "99" a = b; This code exchanges Examples of String operations (concatenation) the values of a and b. int t = a; 1234 99 1234 b = t; expression value operator operator a = b; 99 99 1234 } "Hi, " + "Bob" "Hi, Bob" 99 1234 1234 white } b = t; white "1" + " 2 " + "1" "1 2 1" space space "1234" + " + " + "99" "1234 + 99" Ex 2: spaces "1234" + " + " + "99" "1234" + "99" "123499" space Q. What does this program do? characters
A. No way for us to confirm that it does the exchange! (Need output, stay tuned). Typical use: Input and output.
29 30
Example of computing with strings: subdivisions of a ruler Input and output is necessary for us to provide data to our programs and to learn the result of computations. public class Ruler { command-line Humans prefer to work with strings. arguments public static void main(String[] args) Programs work more efficiently with numbers. { all + ops are concatenation String ruler1 = "1"; String ruler2 = ruler1 + " 2 " + ruler1; 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 String ruler3 = ruler2 + " 3 " + ruler2; Output String ruler4 = ruler3 + " 4 " + ruler3; • System.out.println() method prints the given string. standard output System.out.println(ruler4); } % java Ruler • Java automatically converts numbers to strings for output. Bird's eye view of a Java program } 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
Command-line input ruler1 ruler2 ruler3 ruler4 • Strings you type after the program name are available as args[0], args[1], ... at run time. undefined undefined undefined undefined
ruler1 = "1"; 1 undefined undefined undefined • Q. How do we give an integer as command-line input? ruler2 = ruler1 + " 2 " + ruler1 1 1 2 1 undefined undefined • A. Need to call system method Integer.parseInt() to convert the strings to integers. ruler3 = ruler2 + " 3 " + ruler2 1 1 2 1 1 2 1 3 1 2 1 undefined ruler2 = ruler3 + " 4 " + ruler3 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 Stay tuned for many more options for input and output, and more details on type conversion. 31 32 Input and output warmup: exchange values Data type for computing with integers: int
int data type public class Exchange values integers between 231 and 231 1 { public static void main(String[] args) typical literals 1234 99 -99 0 1000000 Important note: { 32 % java Exchange 5 2 operations add subtract multiply divide remainder Only 2 different int values. int a = Integer.parseInt(args[0]); 2 int b = Integer.parseInt(args[1]); 5 operator + * / % int t = a; not quite the same as integers a = b; % java Exchange 1234 99 b = t; 99 Examples of int operations System.out.println(a); 1234 System.out.println(b); expression value comment Precedence } 5 + 3 8 expression value comment } Java automatically converts int values to String for output 5 - 3 2 3 * 5 - 2 13 * has precedence 5 * 3 15 3 + 5 / 2 5 / has precedence 5 / 3 1 drop fractional part 3 - 5 - 2 -4 left associative 5 % 3 2 remainder Q. What does this program do? ( 3 - 5 ) - 2 -4 better style 1 / 0 runtime error
A. Reads two integers from the command line, then prints them out in the opposite order. Typical usage: Math calculations; specifying programs (stay tuned). 33 34
Example of computing with integers and strings, with type conversion Data type for computing with floating point numbers: double
double data type
values real numbers . public class IntOps × { typical literals 3.14159 -3.0 2.0 1.4142135623730951 6.022e23 Typical double values are approximations public static void main(String[] args) operations add subtract multiply divide remainder { % java IntOps 5 2 Examples: int a = Integer.parseInt(args[0]); 5 + 2 = 7 operator + * / % no double value for π. int b = Integer.parseInt(args[1]); 5 * 2 = 10 int sum = a + b; 5 / 2 = 2 no double value for √ int prod = a * b; 5 % 2 = 1 Examples of double operations no double value for 1/3. int quot = a / b; % java IntOps 1234 99 expression value int rem = a % b; 1234 + 99 = 1333 3.141 + .03 3.171 System.out.println(a + " + " + b + " = " + sum); 1234 * 99 = 122166 Special values System.out.println(a + " * " + b + " = " + prod); 3.141 - .03 3.111 1234 / 99 = 12 expression value System.out.println(a + " / " + b + " = " + quot); 1234 % 99 = 46 6.02e23/2 3.01e23 1.0 / 0.0 Infinity System.out.println(a + " % " + b + " = " + rem); 5.0 / 3.0 1.6666666666666667 } Note: 1234 = 12*99 + 46 10.0 % 3.141 0.577 Math.sqrt(-1.0) NaN } Java automatically converts int values to String for concatenation Math.sqrt(2.0) 1.4142135623730951 "not a number" Typical use: Scientific calculations. 35 36 Other built-in numeric types Excerpts from Java’s Math Library
short data type long data type public class Math double abs(double a) absolute value of a values integers between 215 and 215 1 values integers between 263 and 263 1 double max(double a, double b) maximum of a and b also defined for int, long, and float operations [ same as int ] operations [ same as int ] double min(double a, double b) minimum of a and b
double sin(double theta) sine function float data type double cos(double theta) cosine function inverse functions also available: asin(), acos(), and atan() values approximations to real numbers double tan(double theta) tangent function Degrees in radians. Use toDegrees() and toRadians()) to convert. operations [ same as double ] double exp(double a) exponential (ea)
double log(double a) natural log (loge a, or ln a) Why different numeric types? double pow(double a, double b) raise a to the bth power (ab) • Tradeoff between memory use and range for integers. long round(double a) round to the nearest integer • Tradeoff between memory use and precision for real numbers. double random() random number in [0. 1) double sqrt(double a) square root of a
short int, float double E value of e (constant) long, double You can discard your double PI value of π (constant) calculator now (please). 37 38
Example of computing with floating point numbers: quadratic equation Data type for computing with true and false: boolean