Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 1.1 Your First Program.

Similar presentations


Presentation on theme: "CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 1.1 Your First Program."— Presentation transcript:

1 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS 1.1 Your First Program

2 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 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) n Kids Make Nutritious Snacks. n Red Tape Holds Up New Bridge. n Police Squad Helps Dog Bite Victim. n Local High School Dropouts Cut in Half. (BTW, computers and natural language processing? Yes, a sub-field! Also, computational linguistics, digital humanities, etc.) 4

5 What’s a Program? 5

6 Executing a Program 1:(Comment: Our goal is to find the row of students that has the most students 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." 6

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

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

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

11 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Create, Compile, Execute

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

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

14 14 Programming in Java Some things to note: n 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) n Spacing and Indentation: makes code easier for humans to read HelloWorld.java /******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); }

15 15 Programming in Java Programming in Java. Create the program by typing it into a text editor, and save 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 16 Programming in Java Programming in Java. Create the program by typing it into a text editor, and save 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 % javac HelloWorld.java % java HelloWorld Hello, World command-line (or click the Run button in your IDE)

17 Interactive Development Environments (IDEs) An IDE is a software tool that: n Includes a “smart” editor for your language n Lets you compile all your Java from within the tool n Lets you run the compiled program from within the tool n Supports debugging n 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! 17

18 18

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

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

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

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

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

24 24

25 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…. 25

26 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! } 26

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

28 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) v 0.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 a b. 28

29 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS 1.2 Built-In Types of Data

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

31 31 Basics Definitions. Trace.

32 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Text

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

34 34 Subdivisions of a Ruler % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 "1 2 1" "1 2 1 3 1 2 1" "1" public class Ruler { public static void main(String[] args) { String ruler1 = "1"; String ruler2 = ruler1 + " 2 " + ruler1; String ruler3 = ruler2 + " 3 " + ruler2; String ruler4 = ruler3 + " 4 " + ruler3; System.out.println(ruler4); } string concatenation

35 35 Subdivisions of a Ruler % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 public class Ruler { public static void main(String[] args) { String ruler1 = "1"; String ruler2 = ruler1 + " 2 " + ruler1; String ruler3 = ruler2 + " 3 " + ruler2; String ruler4 = ruler3 + " 4 " + ruler3; System.out.println(ruler4); }

36 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Integers

37 37 Integers int data type. Useful for expressing algorithms.

38 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); } % javac IntOps.java % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46 38 Integer Operations command-line arguments Java automatically converts a, b, and rem to type String 1234 = 12*99 + 46

39 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); } 39 Reading from the Keyboard (p. 126-127) 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

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

41 41 Initializing Variables Q. What happens if I forget to initialize the variable a or b ? n Java compiler does not allow this. n 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 ); } C code uninitialized variable % gcc -o uninit uninit.c % uninit -1073746048

42 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Floating-Point Numbers

43 43 Floating-Point Numbers double data type. Useful in scientific applications.

44 44 Math Library

45 45 Quadratic Equation public class Quadratic { public static void main(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); } Ex. Solve quadratic equation x 2 + bx + c = 0.

46 Testing. Some valid and invalid inputs. 46 % 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 % java Quadratic 1.0 hello java.lang.NumberFormatException: hello % java Quadratic 1.0 java.lang.ArrayIndexOutOfBoundsException Testing command-line arguments not a number golden ratio x 2 – 3x + 2 x 2 – x - 1 x 2 + x + 1

47 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Booleans

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

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

50 50 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. public class LeapYear { public static void main(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

51 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS Type Conversion

52 52 Type Conversion Type conversion. Convert from one type of data to another. n Automatic: no loss of precision; or with strings. n Explicit: cast; or method.

53 53 Random Integer Ex. Generate a pseudo-random number between 0 and N-1. public class RandomInt { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double r = Math.random(); int n = (int) (r * N); System.out.println("random integer is " + n); } String to int (method) double to int (cast) int to double (automatic) int to String (automatic) % java RandomInt 6 random integer is 3 % java RandomInt 6 random integer is 0 % java RandomInt 10000 random integer is 3184 double between 0.0 and 1.0

54 54 Summary A data type is a set of values and operations on those values. String text processing. double, int mathematical calculation. boolean decision making. Be aware. n Declare type of values. n Convert between types when necessary. n In 1996, Ariane 5 rocket exploded after takeoff because of bad type conversion.

55 CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS 1.3 Conditionals and Loops

56 56 Control Flow Control flow. n Sequence of statements that are actually executed in a program. n Conditionals and loops: enable us to choreograph control flow. statement 2 statement 1 statement 4 statement 3 boolean 2 true false statement 2 boolean 1 statement 3 false statement 1 true straight-line control flow control flow with conditionals and loops

57 57 If-Else Statement The if-else statement. A common branching structure. Check boolean condition. If true, execute some statements. n Otherwise, execute other statements. if ( boolean expression ) { statement T ; } else { statement F ; } boolean expression statement F false true if-else syntax if-else flow chart statement T can be any sequence of statements

58 58 If-Else: Leap Year If-else. Take different action depending on value of variable. If isLeapYear is true, then print "is a". Otherwise, print "isn't a ". System.out.print(year + " "); if (isLeapYear) { System.out.print("is a"); } else { System.out.print("isn't a"); } System.out.println(" leap year");

59 59 Oblivious Sorting Sort. Read in 3 integers and rearrange them in ascending order. Puzzle 1. Sort 4 integers with 5 compare-exchanges. Puzzle 2. Sort 6 integers with 12. public class Sort3 { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); if (b > c) { int t = b; b = c; c = t; } if (a > b) { int t = a; a = b; b = t; } if (b > c) { int t = b; b = c; c = t; } System.out.println(a + " " + b + " " + c); } read in 3 integers from command-line swap b and c % java Sort3 9 8 7 7 8 9 % java Sort3 2 1 7 1 2 7 swap a and b swap b and c


Download ppt "CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 1.1 Your First Program."

Similar presentations


Ads by Google