Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 5: September 19-23, 2011 Aditya Mathur Department of Computer Science Purdue.

Similar presentations


Presentation on theme: "CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 5: September 19-23, 2011 Aditya Mathur Department of Computer Science Purdue."— Presentation transcript:

1 CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 5: September 19-23, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA http://www.cs.purdue.edu/homes/apm/courses/CS180Fall2011/ 1.Straight line vs. “wiggly” programs 2.Conditions 3.Loops 4.Quiz 5.Instance and static variables This Week:

2 Readings and Exercises for Week 5 Readings: Chapter 4: 4.1, 4.2, 4.3 [Exclude switch statement] Self help exercises [solutions NOT to be turned in] : 4.1, 4.2, 4.3, 4.4 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 52

3 Announcements 1.Project 1 due on September 23. Planning to submit late? Read the policy for dealing with late submissions. 2.Exam 1 (on 10/3): Details to be discussed next week Wednesday. 3.Register for Piazza if not already done. 4.Register your clickers if not already done. 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 53

4 Conditional execution 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 54 Cookie or no cookie?

5 Straight line program: Single path of execution 9/21/2011 A program that has exactly one path that is traversed when the program is executed. Start Execute a statement End.. Single fixed path ©Aditya Mathur. CS 180. Fall 2011. Week 55

6 Program: Multiple paths of execution 9/21/2011 Start Execute a statement Execute statements Execute a statement End.. condition Execute statements true false true path false path ©Aditya Mathur. CS 180. Fall 2011. Week 56

7 Example: DJ: The problem 9/21/2011 Play music given the genre of user’s choice (R&B or classical). ©Aditya Mathur. CS 180. Fall 2011. Week 57

8 Example: DJ: Algorithm (Textual) 9/21/2011 Get genre requested. if requested genre is R&B then play Byoncè’s “Put a ring on it” else if requested genre is classical then play Mozart’s “Eine Kleine Nacht Music” else Say “sorry I do not have the right music for you.” ©Aditya Mathur. CS 180. Fall 2011. Week 58

9 Example: DJ: Algorithm (Graphical) 9/21/2011 Start Get request End Play Mozart true false Classical R&B? Play Byoncè Apologize How many execution paths? truefalse ©Aditya Mathur. CS 180. Fall 2011. Week 59

10 Conditions 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 510

11 Conditions: Simple 9/21/2011 An expression that evaluates to true or false. int x, y, z ; boolean b; true false x<y x>y+z Math.pow(x,3)>=y z*z-x==y x+3<=y !b Examples : ©Aditya Mathur. CS 180. Fall 2011. Week 511

12 Conditions: Compound 9/21/2011 int x, y, z; boolean b; String s1, s2; x<y &&y==z (x>y+z) || (s1.equals(s2)) Math.pow(x,3)>=y && !(s1.equals(s2)) (z*(z-x))!=y || b && (s1.equals(s2)) (x+3)<=y && b !b || y==0 Examples : An expression that contains two or more simple conditions and evaluates to true or false. ©Aditya Mathur. CS 180. Fall 2011. Week 512

13 Conditions: Dangerous! But survived 9/21/2011 int x, y, p; if (x=y){ p=1; }else { p=2; } if (x==y){ p=1; }else { p=2; } DesiredActual Compiler error! Not a problem, the program will not execute. ©Aditya Mathur. CS 180. Fall 2011. Week 513

14 Conditions: Dangerous! May not survive 9/21/2011 int x, y, p; boolean door1Open=false, door2Open=true; if (door1Open=door2Open){ p=1; }else { p=2; } if (door1Open==door2Open){ p=1; }else { p=2; } DesiredActual No compiler error! Program will execute. What is the value of p? As expected? Then what is the problem? ©Aditya Mathur. CS 180. Fall 2011. Week 514

15 Loops 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 515

16 Problem 9/21/2011 Monitor the pulse rate of a patient every 5 seconds. If the pulse rate is between 60 and 100 then display “Normal”. If the rate is below 60, then display “Low”. If the rate is above 100 then display “High”. ©Aditya Mathur. CS 180. Fall 2011. Week 516

17 Algorithm (Graphical) 9/21/2011 Start if (c) Display “Low” Yes No pR<60 pR in range Display “Normal” Display “High” truefalse Get pulse rate (pR) true false End Range: 60-100 What should be c? Wait for 5 seconds” ©Aditya Mathur. CS 180. Fall 2011. Week 517

18 Algorithm [Textual] 9/21/2011 do forever { get pulse rate; if the pulse rate is between 60 and 100 then Display “Normal”; else if the pulse rate is<60 then Display “Low”; else Display “High”; Wait for 5 seconds; } ©Aditya Mathur. CS 180. Fall 2011. Week 518

19 Loops in Java 9/21/2011 Start condition statements Initialization true statements false End initialization statements; while (condition){ statements; } statements; ©Aditya Mathur. CS 180. Fall 2011. Week 519

20 Problem: Movement of a gas particle 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Assume that a particle is located at the origin (position (0,0)). At each time instance the particle moves randomly one step of length 1 in any one of the four directions: left, up, right, and down. 20 Write a Java program that simulates the behavior of this particle until it has reached a distance of 100 units or more from the origin. Print the number of steps needed to reach 100 units or more. D R U L 1 Move right √ 2 Move up

21 Problem: Solution Step 1 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Let us first write and test a Java program that moves the particle one step in any of the four directions selected randomly. Each direction will be represented by integers 1, 2, 3, and 4 for, respectively, L, U, R, and D. 21 √ 2 If x and y denote the current position of the particle, then the distance from the origin is √( x 2 + y 2 ) In addition to what we have learnt so far, we will use the Java if-statement to solve this problem.

22 Problem: Solution Step 2 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 We will now modify the program written earlier to add a loop so that the particle continues to move while it is at a distance less than 100 units from the origin. write and test a Java program that moves the particle one step in any of the four directions selected randomly. 22 If dist denotes the current distance of the particle from the origin then what condition must be true for the particle to take another step? In addition to what we have learnt so far, we will use the Java while-statement to solve this problem.

23 Live demo 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 523

24 Announcements public boolean feastWithFaculty(Date today){ if(isAnyStudentComing(today)){ return true; }else{ return false; } }// End of feastWithFaculty() 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 524

25 Announcements Project 1 due September 23, 11:59pm. 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 525 Instructions for project turnin are at the course website towards the top of the Lecture schedule page. Make sure you use your correct turnin section number in the document describing instructions for project turnin. Last minute questions on Project 1? Send question to Piazza along with your code. We will try our best to answer quickly.

26 Quiz: 9/21/2011 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 526

27 Q1. Value of x after executing the following ? (a) 2 (b) 1 (c) 3 9/21/2011 if (true) { x=1; }else{ x=2; } ©Aditya Mathur. CS 180. Fall 2011. Week 527 Correct answer: b

28 Q2. Value of z after executing the following? (a) 11 (b) 7 (c) 16 9/21/2011 int x=10, y=15, z=7; if (x+1==y || z>=0) { z=x+1; }else{ z=y+1; }; ©Aditya Mathur. CS 180. Fall 2011. Week 528 Correct answer: a

29 Q3. Value of z after executing the following? (a) 11 (b) 7 (c) 16 9/21/2011 int x=10, y=15, z=7; if (x+1==y && z>=0) { z=x+1; }else{ z=y+1; }; ©Aditya Mathur. CS 180. Fall 2011. Week 529 Correct answer: c

30 Q4. Value of z after executing the following? (a) 11 (b) 16 (c) None of the above 9/21/2011 int x=10, y=11; int z; if ((x+1==y) && y>=11) { z=x+1; }else{ z=y+1; }; ©Aditya Mathur. CS 180. Fall 2011. Week 530 Correct answer: a

31 Q5. Value of x after executing the following? (a) 11 (b) 16 (c) None of the above 9/21/2011 int x=10, y=15; if ((x+1==y) && y==15) { int z=x+1; }else{ int z=y+1; }; x=z; ©Aditya Mathur. CS 180. Fall 2011. Week 531 Correct answer: b

32 Q6. Value of x after executing the following? (a) 20 (b) 19 (c) 9 9/21/2011 int x=10, y=15; if ((x+1==y) && y==15) { int z=x+1; }else{ int z=y+1; }; int z=9; x=x+z; ©Aditya Mathur. CS 180. Fall 2011. Week 532 Correct answer: b

33 Q7. Number of times the marked assignment is executed? (a) 5 (b) 4 (c) 3 (d) 2 9/21/2011 int x=5, count=0; while(count<x){ count=count+1; x=x-1; } ©Aditya Mathur. CS 180. Fall 2011. Week 533 Correct answer: a

34 Scope, instance variables, and static variables 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 534

35 Scope of a name 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Scope is that region in a program where an item (a name) in a declaration can be used. Knowing the scope of the name of an object or a variable allows us to answer the following question: “Can this name be used in this method?” 35

36 Scope: How to find? 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Test{ int myAge, y; Scanner s=new Scanner(System.in); public Test(){ int z=5; myAge=s.nextInt(); } public int getAge(){ return myAge; } public int getZ(){ return z; } }// End of class Scope of a name is defined by where its declaration is placed. If the declaration is inside a class but outside any method then all methods inside the class have access to the name. If the declaration is placed inside a method then all names in the declaration can be used ONLY inside the method. But how about access inside main() to names declared in a class? YES NO YES 36

37 Scope: How to find? 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Test{ int myAge; public Test(){ Scanner s=new Scanner(System.in); } public int getAge(){ myAge==s.nextInt(); return myAge; } }// End of class NO YES s is local to constructor Test, can be used only in this method. myAge is local to class and can be used only in this class. 37

38 Instance variables: Rocket example 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages; double lift; public Rocket(double s, double l){ stages=s; lift=l; }; public double getStage(){ return stages; } }// End of Rocket 38 stages and lift are instance variables. They can be accessed from a Rocket object using the getter and setter methods.

39 Instance variable: Ares Rocket 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages; double lift; public Rocket(double s, double l){ stages=s; lift=l; }; }// End of Rocket 39 stages: 2; lift: 55000; public static void main(String args[]){ Rocket ares1NASA=new Rocket(2, 55000); }

40 Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages; double lift; public Rocket(double s, double l){ stages=s; lift=l; }; public double getStage(){ return stages; } }// End of Rocket 40 stages: 2; lift: 55000; public static void main(String args[]){ Rocket ares1NASA=new Rocket(2, 55000); System.out.println(stages); } NO!

41 Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages; double lift; public Rocket(double s, double l){ stages=s; lift=l; }; public double getStage(){ return stages; } }// End of Rocket 41 stages: 2; lift: 55000; public static void main(String args[]){ Rocket ares1NASA=new Rocket(2, 55000); System.out.println(ares1NASA.stages); } Yes, but Not recommended!

42 Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages; double lift; public Rocket(double s, double l){ stages=s; lift=l; }; public double getStage(){ return stages; } }// End of Rocket 42 stages: 2; lift: 55000; public static void main(String args[]){ Rocket ares1NASA=new Rocket(2, 55000); System.out.println(ares1NASA.getStages()); } Yes!

43 Static variables 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 public class Rocket{ double stages, lift; public static boolean rocketGoesUp =true; public Rocket(double s, double l){ stages=s; lift=l; }; public double getStage(){ return stages; } }// End of Rocket 43 public static void main(String args[]){ Rocket ares1NASA=new Rocket(2, 55000); System.out.println(rocketGoesUp); } Yes! Static variables and methods are common to all objects created from the containing class They can be accessed directly from within their scope without the need for getter and setter methods.

44 More on scope: declarations inside if 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 int x, y; … if( x<y){ int z=3; }else{ int z=-3; } System.out.println(z); 44 No! [Cannot find symbol] Local to the then-part of the statement. Local to the else-part of the statement.

45 More on scope: declarations inside while 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 double num=0; while( num<0.5){ double numX=Math.random(); num=numX; } System.out.println(numX); 45 numX not known here! numX is local to while

46 Problem 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 546

47 Word count 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Write a program that reads an input text and computes and displays the count of the number of occurrences of a given word w. Assume that the text is on one line. Define w in the program. 47

48 Word count: Understand how to solve the problem 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 w=“Ziggy” text=“Hello Ziggy! How are you Ziggy? Bye Ziggy, Bye.” 48 Start Here at index=0 First Occurrence at index 6 Continue at index 11

49 Word count: Algorithm 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 1.Define w. 2.Read text; 3.Initialize count to 0. 4.Initialize startIndex to 0. 5.while(startIndex<length of text){ Search for w from startIndex; If w found then { increment count ; Update startIndex; } 6. Display count. 49

50 Useful methods in the String class: indexOf() 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 int index=text.indexOf(word, from); Returns the index in text from where the first occurrence of word begins. If word does not occur in text then a -1 is returned. 50 Example: String w=“Ziggy”; String text=“Hello Ziggy! How are you Ziggy”; int index=text.indexOf(w, 0); Index will be 6.

51 Useful methods in String class: length() 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Int len=text.length(); Returns the length of the string text. 51 Example: String w=“Ziggy”; int len=w.length() len will be 5.

52 Live demo 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 552

53 Week 5: September 19-23, 2011 Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 553


Download ppt "CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 5: September 19-23, 2011 Aditya Mathur Department of Computer Science Purdue."

Similar presentations


Ads by Google