Lesson Three: Organization

Slides:



Advertisements
Similar presentations
 Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability.
Advertisements

Code Elements and Processing Coordinate System. Code elements: pages Comments: are documentation notes that are ignored by the computer but are.
 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
Lesson Four: More of the Same
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Chapter 6: Functions.
Review Blocks of code {.. A bunch of ‘statements’; } Structured programming Learning Processing: Slides by Don Smith 1.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
PROCESSING Methods. Objectives Be able to define methods that return values Be able to define methods that do not return values Be able to use random.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Lesson Two: Everything You Need to Know
Lesson Two: Everything You Need to Know
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Review Expressions and operators Iteration – while-loop – for-loop.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
Variables. Something to mention… void setup(){ size(200, 200); background(255); smooth(); } void draw() { stroke(0); strokeWeight(abs(mouseX-pmouseX));
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Functions. 2 Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are:
Functions + Overloading + Scope
Chapter 9: Value-Returning Functions
Chapter 6: User-Defined Functions I
Lesson Two: Everything You Need to Know
Functions CIS 40 – Introduction to Programming in Python
Chapter 7 Functions.
Chapter 7 Functions.
Lesson 2: Building Blocks of Programming
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Chapter 4 void Functions
Chapter 10 Algorithms.
6 Chapter Functions.
Chapter 6: User-Defined Functions I
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 10 Algorithms.
ALGORITMA PEMROGRAMAN 2 PROCESSING
Standard Version of Starting Out with C++, 4th Edition
CPS125.
Presentation transcript:

Lesson Three: Organization Chapter 7: Functions Learning Processing Daniel Shiffman Presentation by Donald W. Smith Graphics from text

Lesson Three: Organization 7: Functions Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability 8: Objects Learning Processing: Slides by Don Smith

Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are: setup() background() draw() ellipse() mousePressed() rect() In pseudocode, they might be‘high-level’ headings: Erase background Draw Spaceship Draw enemies Move spaceship based on user keyboard command Move enemies Learning Processing: Slides by Don Smith

Pseudocode to Functions // Modularized draw() void draw() { background(0); drawSpaceShip(); drawEmenies(); moveShip(); moveEnemies(); } Each time through draw: Erase background Draw Spaceship Draw enemies Move spaceship Get keyboard command Move enemies Some functions are ‘built-in’ You can write your own! Learning Processing: Slides by Don Smith

Why use functions? Is your draw()method getting a bit long? Two key principles of good programming: 1) Modularity Break down code into smaller parts More manageable and readable Reduce the number of local variables inside a module 2) Reusability Duplicated code (copy/paste?) is not good Must maintain in multiple places Better to put duplicate code in a new function and ‘call’ it from multiple places Learning Processing: Slides by Don Smith

Exercise 7.1: Modular ‘Pong’ Planning What functions might be used in the game of pong? 1) Decide on the ‘rules’ One player or two player? One player example Two player example 2) Write Pong pseudocode (or flow chart) 3) Decide on function names For user-defined functions 4) Think about variables you will need Local (inside a function) or ‘global’? Create names you can remember Learning Processing: Slides by Don Smith

The Function ‘Definition’ Make a named ‘block’ with the following parts: Return type Function name Parameters area start block void drawShip ( ) { // Variables and code go here } // end drawShip This is also called ‘declaring’ the function You are ‘telling’ the compiler that there is a new named block of code and how it works Other Rules: Define function outside all other functions Name with the same rules as variables (letters, digits, _) Do not use ‘reserved’ words or already used names Learning Processing: Slides by Don Smith

Calling a Function Now that we have a function, let’s use it: void draw() { drawShip(); // note the semicolon! } You ‘Call’ functions from ‘inside’ other functions In this case, inside draw() You call functions by using the function name: Return type Function name Arguments area semicolon <empty> drawShip ( ) ; Learning Processing: Slides by Don Smith

Exercise 7-2: Write and call a function Display a multi-part graphic (or a Zoog!) Learning Processing: Slides by Don Smith

Bouncing Ball without Functions Group code into related ‘chunks’ Learning Processing: Slides by Don Smith

Bouncing Ball with Functions Name the ‘chunks’, declare functions, call them! Learning Processing: Slides by Don Smith

Functions with Arguments and Parameters What if you wanted to use a function to do slightly different things? Some examples you have seen that pass arguments to functions include: size(200,200); color(100,150,0); ellipse(x, y, width, height); More? What if you wanted to write your own function that receives parameters? Learning Processing: Slides by Don Smith

Arguments and Parameters Wikipedia Reference: http://en.wikipedia.org/wiki/Parameter_(computer_science) The book (and many professionals) confuse the two words. Per most texts and Wikipedia: Arguments are ‘sent’ Parameters are ‘received’ Argument comes before Parameter // drawBlackCircle receives size parameter void drawBlackCircle(int diameter) { fill(0); // passes arguments to ellipse() ellipse(50, 50, diameter, diameter); } Learning Processing: Slides by Don Smith

Multiple Arguments void draw() { background(0); // Pass drawCar four arguments drawCar( 100,100,64, color(200,200,0) ); drawCar( 50 ,75 ,32, color(0,200,100) ); drawCar( 80 ,175,40, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … Learning Processing: Slides by Don Smith

Passing Variables void draw() { background(0); int size = 32; // Pass drawCar four arguments drawCar( 100,100,size, color(200,200,0) ); size = size + 16; drawCar( 50 ,75 ,size, color(0,200,100) ); drawCar( 80 ,175,size, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … Learning Processing: Slides by Don Smith

Keys to Passing Arguments You must pass the same number of arguments as defined in the function parameter list. When an argument is passed, it must be of the same type as declared within the parameters in the function definition. An integer must be passed into an integer a floating point into a floating point.. The value you pass as an argument to a function can be a: Literal value (20, 5, 4.3, etc.), Variable (x, y, size, etc.) The result of an expression (8 + 3, 4 * x/2, random(0,10), etc.) Parameters act as local variables inside the receiving function They are only accessible within that function Learning Processing: Slides by Don Smith

Exercise 7-5: Write a function definition: void draw() { float curHourly = 12.25; float raisePct = 9.0; showNewHourly(curHourly, raisePct); } // Make a comment line above the name // return type function name ( parameters ) { // Indented code goes here // Print the new hourly rate } Write your own showNewHourly()function definition to match the function call Learning Processing: Slides by Don Smith

Exercise 7-6: Bouncing Car int globalX = 0; int globalY = 100; int speed = 1; void draw() { background(0); // Call move // Call bounce // Call drawCar with global X and Y and other params; } Write your own function calls to match the functions move, bounce and drawCar Learning Processing: Slides by Don Smith

What am I really passing? Can the receiving function change the variable that you pass? That might be… dangerous… Here are the rules in Processing and Java: All primitive types (int, float, double, char…) are passed by copying the contents of the variable inside the argument into the new parameter variable. Learning Processing: Slides by Don Smith

Pass by Value (Animated) Name of Presentation - Net TeleTrain Pass by Value (Animated) Let's take a closer look at how this works. void draw() { int n = 10; println(n); byValue(n); println(n); } // end draw() void byValue(int num) { num = 73; println(n); } // end byValue() RAM 10 n 10 num 73 August 2002

Wuzzit Do? Learning Processing: Slides by Don Smith

Return types Up until now, you have used a mysterious keyword named void before all of your functions void setup() { void draw() { void byValue(int num) { void drawCar(int x, int y, int thesize, color c) { Remember the parts of a function definition? Return type Function name Parameters area start block void drawShip ( ) { Here is an example that ‘return’ an int: int sum(int a, int b, int c) { int total = a + b + c; return total; // Return a copy of a local variable } Learning Processing: Slides by Don Smith

Assigning the return value to a variable draw calls sum with arguments sum receives values into parameters sum method calculates local total sum method returns copy of total draw assigns returned val to answer void draw() { int answer; answer = sum( 17, 42, 52); println(answer); noLoop(); } int sum(int a, int b, int c) { int total = a + b + c; return total; Learning Processing: Slides by Don Smith

A useful example: Distance between 2 pts float distance(float x1, float y1, float x2, float y2) { float dx = x1 – x2; // one side of the right triangle float dy = y1 – y2; // other side of the right triangle float d = sqrt(dx*dx + dy*dy); // hypoteneuse length return d; } Processing has a dist()function that does the same thing… Learning Processing: Slides by Don Smith

Summary Functions are useful for many tasks 1) Break code into smaller ‘named’ chunks 2) Prevent duplication of code 3) Make useful ‘utilities’ that can be reused Processing is really a ‘function library’ Provides functions such as line(), ellipse(), rect() You can write code inside functions that Processing calls setup() and draw() You can define your own functions Pass ‘arguments’ to functions to tell them what to do They are received as ‘parameters’ Primitive types are passed by value Functions can return values Learning Processing: Slides by Don Smith