1 / 59

1.1 Your First Program

1.1 Your First Program. Why Programming?. Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." Prepackaged software solutions. Great, if it does exactly what you need.

Download Presentation

1.1 Your First Program

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 1.1 Your First Program

  2. Why Programming? Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity." Prepackaged software solutions. Great, if it does exactly what you need. Computer programming. Art of making a computer do what you want. Ada Lovelace Analytic Engine

  3. Languages Machine languages. Tedious and error-prone. “Natural” languages. Ambiguous and hard for computer to parse. High-level programming languages. Acceptable tradeoff. Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. - Donald Knuth

  4. Real newspaper headlines (compiled by Rich Pattis) • Kids Make Nutritious Snacks. • Red Tape Holds Up New Bridge. • Police Squad Helps Dog Bite Victim. • Local High School Dropouts Cut in Half. (BTW, computers and natural language processing? Yes, a sub-field! Also, computational linguistics, digital humanities, etc.)

  5. What’s a Program?

  6. Executing a Program 1: (Comment: Our goal is to find the row of students that has the moststudents who have birthdays in August.) 2: For each row R in your section, do the following: 3: Let N be the number of students in the current row R. 4: If N is equal to 0, skip to instruction on line 17. 5: Otherwise, N is greater than 0 -- do the following steps: 6: (Comment: the next section's goal is to count how many students 7: For each student S in the row, do the following: 8: Ask if his or her birthday is in August. 9: If "yes", then add 1 to your count of August-birthdays in this row. 10: (End of the steps for each student in the row.) 11: (Comments: the next section's goal is to see if this is larger than previous best.) 12: If the count is larger than your maximum-so-far value, then do the following: 13: Update your maximum-so-far value to be the count for that row. 14: Let Row-ID be the name of the student sitting on the aisle. 15: (End of steps for when count > max-so-far.) 16: (End of steps for when number of students N is greater than 0.) 17: (Now, go to the next row! If no more rows, go to next step.) 18: Report the following: "The row where Row-ID is on the aisle has maximum-so-far August birthdays. That is the most for any row in my section."

  7. Why Java? Java features. • Widely used. • Widely available. • Embraces full set of modern abstractions. • Variety of automatic checks for mistakes in programs. Java economy. • Mars rover. • Cell phones. • Blu-ray Disc. • Web servers. • Medical devices. • Supercomputing. • … James Gosling http://java.net/jag $100 billion,5 million developers

  8. Why Java? Java features. • Widely used. • Widely available. • Embraces full set of modern abstractions. • Variety of automatic checks for mistakes in programs. Caveat. There are only two kinds of programming languages: those people always [gripe] about and those nobody uses. - Bjarne Stroustrup

  9. Why Java? Java features. • Widely used. • Widely available. • Embraces full set of modern abstractions. • Variety of automatic checks for mistakes in programs. Caveat. No perfect language. Our approach. • Minimal subset of Java. • Develop general programming skills that are applicable to:C, C++, C#, Perl, Python, Ruby, Matlab, Fortran, Fortress, …

  10. A Rich Subset of the Java Language Built-In Types System Math Library int double System.out.println() Math.sin() Math.cos() long String System.out.print() Math.log() Math.exp() char boolean System.out.printf() Math.sqrt() Math.pow() Math.min() Math.max() Math.abs() Math.PI Flow Control Parsing if else Integer.parseInt() Primitive Numeric Types for while Double.parseDouble() + - * / % ++ Boolean Punctuation -- > < true false { } <= >= == || && ( ) ! , ; != String Arrays Objects + "" a[i] class static length() compareTo() new public private charAt() matches() a.length toString() equals() new main()

  11. Create, Compile, Execute

  12. Programming in Java Programming in Java. • Create the program by typing it into a text editor, andsave it as HelloWorld.java • Read more: page 5 of textbook /******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/ publicclass HelloWorld { publicstaticvoid main(String[] args) { System.out.println("Hello, World"); } } HelloWorld.java

  13. Programming in Java Issue for Beginners Using Java. • Confusing! What are those first two lines of code all about?! • For now: think of the program you write as only being the line “inside” that thing called main • New program? Make a copy of this file HelloWorld.java, and rename both the file and the class (line 1 of the code) /******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/ publicclass HelloWorld { publicstaticvoid main(String[] args) { System.out.println("Hello, World"); } } HelloWorld.java

  14. Programming in Java Some things to note: • Comments: • not instructions for the computer, for human readers • /* a comment */ or // comment to end of line • Pairs of “delimiters”: {…} “…” (…) […] • Curly-brackets: blocks of code that are one “unit” somehow (more on this later) • Spacing and Indentation: makes code easier for humans to read /******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/ publicclass HelloWorld { publicstaticvoid main(String[] args) { System.out.println("Hello, World"); } } HelloWorld.java

  15. Programming in Java Programming in Java. • Create the program by typing it into a text editor, andsave it as HelloWorld.java • Compile it by typing at the command-line:javac HelloWorld.java • This creates a Java bytecode file named: HelloWorld.class command-line % javac HelloWorld.java (or click the Compile button in your IDE)

  16. Programming in Java Programming in Java. • Create the program by typing it into a text editor, andsave it as HelloWorld.java • Compile it by typing at the command-line:javac HelloWorld.java • Execute it by typing at the command-line:java HelloWorld command-line % javac HelloWorld.java % java HelloWorld Hello, World (or click the Run button in your IDE)

  17. Interactive Development Environments (IDEs) • An IDE is a software tool that: • Includes a “smart” editor for your language • Lets you compile all your Java from within the tool • Lets you run the compiled program from within the tool • Supports debugging • Supports many other programmer needs, especially for large programs Example IDEs for Java: DrJava (for beginners) Eclipse (powerful!) Important to know how Java programs are built and run without using IDEs!

  18. What you know after Lab 0! • A Java program is created in a .java file. • First line defines the class/program and the name. • The name of the class must match name of .java file • Second line defines main() method. • (For now) your program is set of statements in main().

  19. What you know after Lab 0! • A Java statement ends in a semi-colon. • Sometimes statements are grouped inside { and }. • Curly-brackets must nest properly. • Comments are indicated by // or by /* ... */ • How Java treats whitespace. • Indentation and spacing are important of human readers.

  20. What you know after Lab 0! • Data in a running program is stored in a variable. • Variables have a type (int, double, String). • Variables are declared with a name and type, and can be initialized. • Literal values can be assigned to variables.

  21. What you know after Lab 0! • Methods have a name and invoke some operation or function on some data. • Example: System.out.println("Hiya!"); • Some methods return a value that can be used. • Example: Math.sqrt(100) • Methods like these are part of Java's Standard Library.

  22. What you know after Lab 0! • Java programs (.java files) are compiled. • This creates a .class file. • The class file contains machine instructions. • To run the program, execute the class file.

  23. A More Complicated Example (for Lab 0) // This is a comment at the top of class/program Demo1 public class Demo1 { public static void main(String[] args) { // program statements go inside method main System.out.println("Hello world!"); int x = 3; System.out.println("The value of variable x is: " + x); x = x + 3; System.out.println("Now the value of variable x is: " + x); // continued….

  24. Lab 0 Example continued double pi = 3.14; System.out.println("The value of variable pi is: " + pi); double someValue = Math.sqrt(x); System.out.println("The sqrt of x is: " + someValue); System.out.println("The sqrt of 100 is: " + Math.sqrt(100)); String message = "Psst! We said pi is " + pi + "!!!"; System.out.println("Message is: " + message); // we're done! }

  25. Typical Scenario for Solving Problems with a Program • Gather requirements • Develop high-level approach • Rough break-down of the parts (maybe) • Algorithms • Pseudo-code (maybe) • Choose language, and then choose IDE • Design test cases (both “positive” and “negative”) • Iterate until requirements met (maybe create new requirements!) • Write code • Test • Debug (fix) • Use the finished code to solve the problem at hand

  26. Let’s Solve a Problem with a Program! • The book and booksite has many examples:http://www.cs.princeton.edu/introcs/12types/ • Problem 1.2.18: If x and y represent a point (x,y) in a Cartesian plane, print the distance to the origin. • Version 2: find distance from (x1,y1) to (x2,y2) • Problem 1.2.25: Wind chill. Given the temperature t and wind-speed v, we define the wind chill to be: w = 35.74 + 0.6215 t - (0.4275 t - 35.75) v0.16 Write a program WindChill.java that reads two double values t and v and prints out the wind chill. Use Math.pow(a, b) to compute ab.

  27. 1.2 Built-In Types of Data

  28. Built-in Data Types Data type. A set of values and operations defined on those values. type set of values literal values operations char characters 'A' '@' compare String sequences of characters "Hello World" "CS is fun" concatenate int integers 17 12345 add, subtract, multiply, divide double floating point numbers 3.1415 6.022e23 add, subtract, multiply, divide boolean truth values true false and, or, not

  29. Basics Definitions. Trace.

  30. Text

  31. Text String data type. Useful for program input and output.

  32. Subdivisions of a Ruler publicclass Ruler { publicstaticvoidmain(String[] args){ String ruler1 ="1"; String ruler2 = ruler1 +" 2 "+ ruler1; String ruler3 = ruler2 +" 3 "+ ruler2; String ruler4 = ruler3 +" 4 "+ ruler3; System.out.println(ruler4); } } "1" "1 2 1" "1 2 1 3 1 2 1" string concatenation % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

  33. Subdivisions of a Ruler publicclass Ruler { publicstaticvoidmain(String[] args){ String ruler1 ="1"; String ruler2 = ruler1 +" 2 "+ ruler1; String ruler3 = ruler2 +" 3 "+ ruler2; String ruler4 = ruler3 +" 4 "+ ruler3; System.out.println(ruler4); } } % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

  34. Integers

  35. Integers intdata type. Useful for expressing algorithms.

  36. Integer Operations public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } } command-linearguments % javac IntOps.java % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46 Java automatically convertsa, b , and rem to type String 1234 = 12*99 + 46

  37. Reading from the Keyboard (p. 126-127) public class IntOps { public static void main(String[] args) { int a = StdIn.readInt(); int b = StdIn.readInt(); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } } Calls to book’s library function to read an int value from keyboard • StdIn.readint() and StdIn.readDouble() etc. (see pages 127-127) • Library methods, just like sqrt() and System.out.println() • Not standard Java, but created by our textbook authors • Must have the Java file StdIn.java in same directory as your code

  38. Initializing Variables Q. What happens if I forget to initialize the variable a or b? • Java compiler does not allow this. • Caveat: in other languages, variable initialized to arbitrary value. Q. What do you mean, arbitrary?

  39. Initializing Variables Q. What happens if I forget to initialize the variable a or b? • Java compiler does not allow this. • Caveat: in other languages, variable initialized to arbitrary value. Q. What do you mean, arbitrary? int main(int argc, char*argv[]) { int whoops; printf("%d\n", whoops ); } uninitialized variable % gcc -o uninit uninit.c % uninit -1073746048 C code

  40. Floating-Point Numbers

  41. Floating-Point Numbers doubledata type. Useful in scientific applications.

  42. Math Library

  43. Quadratic Equation Ex. Solve quadratic equation x2 + bx + c = 0. publicclass Quadratic { publicstaticvoidmain(String[] args){ // parse coefficients from command-line double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); // calculate roots double discriminant = b*b -4.0*c; double d = Math.sqrt(discriminant); double root1 =(-b + d)/2.0; double root2 =(-b - d)/2.0; // print them out System.out.println(root1); System.out.println(root2); } }

  44. Testing Testing. Some valid and invalid inputs. % java Quadratic –3.0 2.0 2.0 1.0 % java Quadratic –1.0 –1.0 1.618033988749895 -0.6180339887498949 % java Quadratic 1.0 1.0 NaN NaN % java Quadratic 1.0 hello java.lang.NumberFormatException: hello % java Quadratic 1.0 java.lang.ArrayIndexOutOfBoundsException x2 – 3x + 2 command-line arguments x2 – x - 1 golden ratio x2 + x + 1 not a number

  45. Booleans

  46. Booleans boolean data type. Useful to control logic and flow of a program.

  47. Comparisons Comparisons. Take operands of one type and produce an operand of type boolean.

  48. Leap Year Q. Is a given year a leap year? A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100. publicclass LeapYear { publicstaticvoidmain(String[] args){ int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 but not 100 isLeapYear =(year %4==0) &&(year %100!=0); // or divisible by 400 isLeapYear = isLeapYear ||(year %400==0); System.out.println(isLeapYear); } } % java LeapYear 2004 true % java LeapYear 1900 false % java LeapYear 2000 true

More Related