COSC 1P02 Introduction to Computer Science 3.1 Cosc 1P02 Week 3 Lecture slides Birthdays are good for you. Statistics show that the people who have the.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Procedural programming in Java
Chapter 7: User-Defined Functions II
Cosc 1P02 Week 2 Lecture slides
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Computer Science 1620 Loops.
Road Map Introduction to object oriented programming. Classes
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
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.
Introduction to Methods
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
COSC 1P02 Intro. to Computer Science 1.1 Cosc 1P02 Week 1 Lecture slides "If a man does his best, what else is there?” General George S. Patton ( )
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Methods in Java CSC1401. Overview In this session, we are going to see how to create class-level methods in Java.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Procedural programming in Java Methods, parameters and return values.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
COSC 1P02 Introduction to Computer Science 5.1 Cosc 1P02 Week 5 Lecture slides Psychiatrist to patient "You have nothing to worry about - anyone who can.
COP 2220 Computer Science I Topics –Breaking Problems Down –Functions –User-defined Functions –Calling Functions –Variable Scope Lecture 4.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Arrays Chapter 7.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 9: Value-Returning Functions
User-Written Functions
Chapter 7: User-Defined Functions II
Testing and Debugging.
Programming Fundamentals Lecture #7 Functions
Chapter 4: Writing Classes
Chapter 4 void Functions
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
Group Status Project Status.
Loops and Iteration CS 21a: Introduction to Computing I
Corresponds with Chapter 5
Methods Coding in Java Copyright © Curt Hill.
Presentation transcript:

COSC 1P02 Introduction to Computer Science 3.1 Cosc 1P02 Week 3 Lecture slides Birthdays are good for you. Statistics show that the people who have the most live the longest. (Rev. Larry Lorenzoni)

COSC 1P02 Introduction to Computer Science 3.2 Review  Memory Representation of:  Value variables  Reference variables  Assignment of reference variables  Tiling patterns

COSC 1P02 Introduction to Computer Science 3.3 Dealing with Complexity  Limits on composition  Can only go so deep before the nesting becomes un- manageable.  Requires separate index variables for each loop  Repetition of code  Duplicating code in a program is a bad thing  Increases complexity unnecessarily  More work.  Abstraction  Divide and conquer  Break problems into chunks  Let the process (code) be independent from operation of calling the code.  E.g. Yertle.forward(40); runs magic code to move yertle.

COSC 1P02 Introduction to Computer Science 3.4 Two Squares  Consider drawing two squares at different places on the screen  repeated code  increased possibility of error  Drawing a square could be considered an operation (like drawing a line)  drawing a line done by a method ( forward )  write a method to draw a square ( drawSquare )  Example

COSC 1P02 Introduction to Computer Science 3.5 Methods  Method declaration  syntax  name  verb  body  Method call  syntax  Method execution  current code suspended  body of method executed  current code continues

COSC 1P02 Introduction to Computer Science 3.6 Eight Squares Revisited eightSquares2.java  Composition via methods  use method call instead of nesting  Example  Reduced complexity  Can think of drawing a square as a basic operation  don’t have to worry about how it is done  code for EightSquares simpler  don’t have to worry about different index variables

COSC 1P02 Introduction to Computer Science 3.7 Scope  Declarations occur at different places  in class  in method  in for statement  Scope  Where are names defined in declarations useable?  Rule  in class – from { in class header to } at end of class  includes methods names  in method – from { in method header to } at end of method  in for – body of for (statements between { } )  Example  Composition via nesting vs via methods  non-interference

COSC 1P02 Introduction to Computer Science 3.8 Eight Squares2 public class EightSquares2 { private Turtleyertle;// turtle for drawing private TurtleDisplayer display; public EightSquares2 ( ) { int i; yertle = new Turtle(); display = new TurtleDisplayer(yertle); for ( i=1 ; i<=8 ; i++) { drawSquare(); yertle.right(PI/4); }; };// constructor private void drawSquare() { yertle.penDown(); for (int i=1 ; i<=4 ; i++) { yertle.forward(40); yertle.right(PI / 2); }; yertle.penUp(); };// drawSquare public static void main ( String args[] ) { new EightSquares2(); }; }// EightSquares2 This i is local and visible to entire constructor Visible within for loop only Modification of i in drawSquare does not affect the i in the constructor Declared at the class level, visible over entire class.

COSC 1P02 Introduction to Computer Science 3.9 What is an Object  An Object has 2 parts  Memory  What it remembers  State information  Data  Behaviour  What an object can do  Actions which can be performed  A Class defines what an object is:  Instance Variables represent the memory  Methods define the behaviour

COSC 1P02 Introduction to Computer Science 3.10 Object Creation  New causes an object to be created from the template (class)  E.g. new Turtle();  An Object is initialized when it is created.  Initial memory and behaviour are set  New causes the constructor to run to create the object  Constructor  Is a method (initial behaviour)  Has the same name as the class  New causes the constructor to execute.

COSC 1P02 Introduction to Computer Science 3.11 Constructors, Methods & Objects  Methods are executed by an object  who is executing drawSquare ?  no object specified  Turtle (yertle) doesn't know how  main method  is a method declaration  every Java program must have ate least one class (called the main class) that has a main method  Execution begins in body of main method  body includes object creation ( new )  creates a new EightSquares object  on creation object executes its constructor  Local method call  when no object specified method is executed by same object as is executing the method call (e.g. the EightSquares object)  drawSquare() is shorthand for this.drawSquare()

COSC 1P02 Introduction to Computer Science 3.12 Eight Squares public class EightSquares2 { private TurtleDisplayer display; // display to draw on private Turtle yertle; // turtle to do drawing /** The constructor draws 8 squares in a pattern. */ public EightSquares2 ( ) { display = new TurtleDisplayer(); yertle = new Turtle(30); display.setTurtle(yertle); yertle.penDown(); for ( int i=1 ; i<=8 ; i++ ) { drawSquare(); yertle.right(PI/4); }; yertle.penUp(); display.close(); }; // constructor /** This method draws a square with the current turtle position as the * top-left corner. */ private void drawSquare ( ) { yertle.penDown(); for ( int i=1 ; i<=4 ; i++ ) { yertle.forward(40); yertle.right(PI/2); }; yertle.penUp(); }; // drawSquare public static void main ( String[] args ) { new EightSquares2(); }; EightSquare2 object is created Constructor creates object, identified as by same name as the class Method drawSquare is called, control is passed to the method. Method code is executed Control is passed back from where it was called. Rest of code is executed. When constructor finishes then control goes back to main.

COSC 1P02 Introduction to Computer Science 3.13 Eight Squares One More Time  Constructor is meant to initialize an object  Separate initialization from operation  Puts object into a known state.  write operations as methods  e.g. Turtle  Example  constructor simply creates display, turtle and connects them  method draw performs the operation to draw the eight squares  draw is executed by the EightSquares object created in main  E.g. new EightSquares3().draw();  New EightSquares3() creates an object returning a reference .draw then calls the behavior of the new object.

COSC 1P02 Introduction to Computer Science 3.14 Hexagon Revisited  Complex scene with many figures  hard to keep track of where drawing begins & ends  Centre figure on a point with a size of the figure (rather than a side)  method to draw figure starts from center & leaves pen in center  i.e. leaves turtle in same state as it started  Turtle state becomes independent from drawing.  Geometry of a hexagon  Drawing a hexagon  move out from center  position down first side  draw sides  return to center & pen orientation  Example

COSC 1P02 Introduction to Computer Science 3.15 Geometry of a Hexagon - Half of this angle is then  /6 Facts about Polygons The size of the interior angle is 2  / the number of point. - For a Hexagon this would be 2*  /6. By taking half of the interior angle we create a right angled triangle. We can now calculate the opposite side using standard trigonometry. - For our Hexagon this would be r*sin  /6 - For any polygon this would be r*sin  /sides The entire side would be 2 * this quantity. - For a Hexagon 2*r*sin  /6 - For a Polygon 2*r*sin  /sides We need to calculate the initial angle of rotation. If this is the angle    /2-  Then to opposite angle is  /2-   /2-  Which is also this angle We now can do some simple subtraction  -(  /2-  ) gives us the angle we are looking for. This reduces to  /2+  This angle To get subsequent angles of rotation. We can note that these angles are the same. So….  -2(  /2-  ) = 2  For a hexagon this becomes  /3  /2- 

COSC 1P02 Introduction to Computer Science 3.16 Expressions  Computations specified by expressions  like algebraic expressions in Mathematics  written on one line  Composed of  operators  constants  variables  functions  Evaluation order  by priority, left to right  parentheses to force order

COSC 1P02 Introduction to Computer Science 3.17 Two Hexagons  Consider drawing two hexagons of different size  Size of hexagon fixed in method  different methods for different sizes?  essentially identical code  differs only by value of radius  Allow the method to vary depending on value of radius  Example  radius is parameter

COSC 1P02 Introduction to Computer Science 3.18 Two Hexagon. public TwoHexagon ( ) { display = new TurtleDisplayer(); yertle = new Turtle(); display.setTurtle(yertle); }; // constructor private void draw ( ) { yertle.moveTo(-75,75); drawHexagon(40); yertle.moveTo(75,-75); drawHexagon(60); display.close(); }; // constructor private void drawHexagon ( double radius ) { //Rest of code next page Radius take on the value 40 Rest of drawHexagon executes using radius, on method completion drawHexagon returns Radius take on the value 60

COSC 1P02 Introduction to Computer Science 3.19 Two Hexagon.. private void drawHexagon ( double radius ) { double angle; // exterior angle between sides of hexagon double side; // length of side of hexagon angle = 2 * PI / 6; side = 2 * radius * sin(PI/6); yertle.forward(radius); yertle.right(PI/2+PI/6); yertle.penDown(); for ( int i=1 ; i<=6 ; i++) { yertle.forward(side); yertle.right(angle); }; yertle.penUp(); yertle.left(PI/2+PI/6); yertle.backward(radius); }; // drawHexagon The value of radius is then used in the method.

COSC 1P02 Introduction to Computer Science 3.20 Parameters  Allows a method to be generalized over one or more values  radius for drawHexagon  Parameter (formal parameter)  declared in method header  behaves like a local variable within method body  scope is method body  is initialized to value of argument at call  Argument (actual parameter)  an expression that produces a value of the declared type  constant  variable  expression  Method execution  value of argument computed  calling code suspended  value of argument copied to parameter  body of method executed  calling code continues

COSC 1P02 Introduction to Computer Science 3.21 Polygons  Code for drawing all regular closed figures (polygons) similar  move out from center  rotate to facing down first side  for each side  draw side  rotate to next side  move back to center  Geometry of a polygon  Code would depend on two values: radius and number of sides  method with two parameters  Example  Note: number of times in for loop now a variable  index i counts from 1 to value of nSides

COSC 1P02 Introduction to Computer Science 3.22 Polygons private void draw ( ) { yertle.left(PI/2); // facing up so point of polygon is at top yertle.moveTo(-75,75); drawPolygon(5,20); yertle.moveTo(75,75); drawPolygon(6,30); yertle.moveTo(75,-75); drawPolygon(7,40); yertle.moveTo(-75,-75); drawPolygon(8,50); display.close(); }; // draw private void drawPolygon ( int nSides, double radius ) { double angle; // exterior angle between sides of polygon double side; // length of side of polygon angle = 2 * PI / nSides; side = 2 * radius * sin(PI/nSides); yertle.forward(radius); yertle.right(PI/2+PI/nSides); yertle.penDown(); for ( int i=1 ; i<=nSides ; i++) { yertle.forward(side); yertle.right(angle); }; yertle.penUp(); yertle.left(PI/2+PI/nSides); yertle.backward(radius); }; // drawPolygon When the method is called each actual parameter is assigned to its formal parameter Formal parameters are then used in the method body.

COSC 1P02 Introduction to Computer Science 3.23 The end