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.

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

Logic & program control part 3: Compound selection structures.
Two examples of Problem Solving in Programming H. Chad Lane University of Pittsburgh CS7: Introduction to Programming.
BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
CS 180 Problem Solving and Object Oriented Programming Spring 2011 February 16, 2011 Aditya Mathur Department of Computer Science Purdue University West.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 13: Nov 14-18, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 4: September 12-16, 2011 Aditya Mathur/Tim Korb Department of Computer.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 13: Nov 15-19, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 16: Dec 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 9: Oct 17-21, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for the Final Lecture Dec 7, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 6: September 26-30, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 3: September 5-9, 2011 Aditya Mathur Department of Computer Science Purdue.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 20, 2004 Last update:
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Lecture 7. Review Homework 1 (sample solution) Project 1 will be assigned next week –Draw a picture (whatever you want) in the world by using turtles.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 4.
MrsBillinghurst. net A2 Computing A2 Computing Projects Game Animation in Pascal.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 11: Oct 31-Nov 4, 2011 Aditya Mathur Department of Computer Science Purdue.
CS1101: Programming Methodology Aaron Tan.
Getting Started with Java Recitation – 1/23/2009 CS 180 Department of Computer Science, Purdue University.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 3: September 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CPS120: Introduction to Computer Science Decision Making in Programs.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 5: September 20-24, 2010 Aditya Mathur Department of Computer Science Purdue.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 11: Nov 1-5, 2010 Aditya Mathur Department of Computer Science Purdue University.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 14: Nov 21-25, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 6: September 27-Oct 1, 2010 Aditya Mathur Department of Computer Science.
Repetition Statements
Building Java Programs
Building Java Programs
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I – Exercises UTPA – Fall 2012 This set of slides is revised from lecture.
The University of Texas – Pan American
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises UTPA – Fall 2012 This set of slides is revised from.
CS 200 Primitives and Expressions
Building Java Programs
Building Java Programs
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
Using Objects (continued)
CSC 1051 – Data Structures and Algorithms I
Building Java Programs
Building Java Programs
Building Java Programs
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
CS Problem Solving and Object Oriented Programming Spring 2019
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

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 1.Straight line vs. “wiggly” programs 2.Conditions 3.Loops 4.Quiz 5.Instance and static variables This Week:

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 Week 52

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 Week 53

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

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 Week 55

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 Week 56

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 Week 57

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 Week 58

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 Week 59

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

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 Week 511

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 Week 512

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 Week 513

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 Week 514

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

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 Week 516

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: What should be c? Wait for 5 seconds” ©Aditya Mathur. CS 180. Fall Week 517

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 Week 518

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 Week 519

Problem: Movement of a gas particle 9/21/2011©Aditya Mathur. CS 180. Fall 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

Problem: Solution Step 1 9/21/2011©Aditya Mathur. CS 180. Fall 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.

Problem: Solution Step 2 9/21/2011©Aditya Mathur. CS 180. Fall 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.

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

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 Week 524

Announcements Project 1 due September 23, 11:59pm. 9/21/2011©Aditya Mathur. CS 180. Fall 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.

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

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 Week 527 Correct answer: b

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 Week 528 Correct answer: a

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 Week 529 Correct answer: c

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 Week 530 Correct answer: a

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 Week 531 Correct answer: b

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 Week 532 Correct answer: b

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 Week 533 Correct answer: a

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

Scope of a name 9/21/2011©Aditya Mathur. CS 180. Fall 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

Scope: How to find? 9/21/2011©Aditya Mathur. CS 180. Fall 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

Scope: How to find? 9/21/2011©Aditya Mathur. CS 180. Fall 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

Instance variables: Rocket example 9/21/2011©Aditya Mathur. CS 180. Fall 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.

Instance variable: Ares Rocket 9/21/2011©Aditya Mathur. CS 180. Fall 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); }

Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 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!

Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 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!

Instance variable: Accessing data inside an object 9/21/2011©Aditya Mathur. CS 180. Fall 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!

Static variables 9/21/2011©Aditya Mathur. CS 180. Fall 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.

More on scope: declarations inside if 9/21/2011©Aditya Mathur. CS 180. Fall 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.

More on scope: declarations inside while 9/21/2011©Aditya Mathur. CS 180. Fall 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

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

Word count 9/21/2011©Aditya Mathur. CS 180. Fall 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

Word count: Understand how to solve the problem 9/21/2011©Aditya Mathur. CS 180. Fall 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

Word count: Algorithm 9/21/2011©Aditya Mathur. CS 180. Fall 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

Useful methods in the String class: indexOf() 9/21/2011©Aditya Mathur. CS 180. Fall 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.

Useful methods in String class: length() 9/21/2011©Aditya Mathur. CS 180. Fall 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.

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

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 Week 553