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

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Variables in C Amir Haider Lecturer.
Basic Java Constructs and Data Types – Nuts and Bolts
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Writing Pseudocode And Making a Flow Chart A Number Guessing Game
Credit hours: 4 Contact hours: 50 (30 Theory, 20 Lab) Prerequisite: TB143 Introduction to Personal Computers.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
DIVIDING INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
Chapter 7: Arrays In this chapter, you will learn about
Variables Conditionals Boolean Expressions Conditional Statements How a program produces different results based on varying circumstances if, else if,
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
Objects. 2 Object Oriented Programming (OOP) OOP is a different way to view programming Models the real world A different view than Structured programming.
Programming Methodology (1). public class Hello { public static void main(String[] args) { System.out.println("Hello world"); } } Hello world.
Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Spring Semester 2013 Lecture 5
Week 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Procedural programming in Java
 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
Variables Conditionals Loops The concept of Iteration Two types of loops: While For When do we use them? Iteration in the context of computer graphics.
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.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
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.
CS 201 Functions Debzani Deb.
Lesson Three: Organization
Topic 4 – Programmer- Defined Functions. CISC 105 – Topic 4 Functions So far, we have only seen programs with one function, main. These programs begin.
Introduction to Methods
Chapter 6: Functions.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Review Blocks of code {.. A bunch of ‘statements’; } Structured programming Learning Processing: Slides by Don Smith 1.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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 06 (Part I) Functions and an Introduction to Recursion.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Functions. Functions are named blocks of code. Functions allow complex programs to be broken down into smaller, simpler tasks. Functions allow commonly.
CPS120: Introduction to Computer Science Functions.
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.
Procedural programming in Java Methods, parameters and return values.
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.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Continuous. Flow of Control Programs can broadly be classified as being –Procedural Programs are executed once in the order specified by the code varied.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
11 Adding a Bread Bat Session Session Overview  We have created a cheese sprite that bounces around the display  We now need to create a bread.
Review Expressions and operators Iteration – while-loop – for-loop.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Variables. Something to mention… void setup(){ size(200, 200); background(255); smooth(); } void draw() { stroke(0); strokeWeight(abs(mouseX-pmouseX));
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:
Chapter 7 Functions.
Chapter 7 Functions.
Chapter 4 void Functions
Chapter 10 Algorithms.
6 Chapter Functions.
Chapter 10 Algorithms.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 10 Algorithms.
ALGORITMA PEMROGRAMAN 2 PROCESSING
CPS125.
Introducing Modularity
Presentation transcript:

 Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability 2

Functions are a means of taking the parts of our program and separating them out into modular pieces, making our code easier to read, as well as revise. Functions can go by other names such as: procedures methods subroutines  We have been somewhat limited to two main functions : setup(); draw(); 3

 Isn't your draw() method getting a bit long?  Two key principles of good programming: 1) Modularity: The break down of code into smaller parts *The code becomes more manageable and readable *Also reduces the number of local variables inside a module 2) Reusability Duplicated code (copy/paste?) is not good Because you must maintain it in multiple places Wouldn't it be better to put duplicate code in a new function and ‘call’ it from multiple places 4

What is a function? Simply, it's a named block of code Some examples that you already know are: setup()background() draw()ellipse() mousePressed()rect() There are more to these functions, but it has been tucked away out of sight. We simply use them by adding in values that the function uses within itself. i.e.background(R, G, B); But we have not been too concerned with that part.. Until now. 5

Before writing a function, think about the different parts or key actions of your program. If we were to write a simple game like space invaders we could break down the code into smaller key parts such as: Each time through draw: Erase background Draw Spaceship Draw enemies Move spaceship Get keyboard command Move spaceship Move enemies Some functions are ‘built-in’ like we have seen The good news is you can write your own functions! 6

This is how it might look after you have broken down your program into functions: 7 // Modularized void draw() { background(0); drawSpaceShip(); drawEmenies(); moveShip(); moveEnemies(); } All the code for each function is "tucked away" out of sight. This makes for cleaner more organized code and easier to debug!

Let's think about 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 8

 The parts of a function Return type Function name Parameters area start block void drawShip ( ) { // Variables and code go here } // end block 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 below draw() Name with the same rules as variables (letters, digits, _) Do not use ‘reserved’ words or already used names 9

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: drawShip( ); // this calls the function 10

11 void drawBlackCircle ( ) { // this declares and names the functions and begins the bock of code fill(0); ellipse ( 250, 150, 75,75); } // end block drawBlackCircle function The function will be declared outside of setup() and draw() but it has to be called from within a function. The entire code void setup(){ size(500, 500); } void draw(){ background( 150); drawBlackCircle ( ); // calls the function } // end draw block // declares the function void drawBlackCircle ( ) { //declared outside of the function fill(0); ellipse ( 250, 150, 75,75); }

 Group code into related ‘chunks’ 12

13 // Declare all global variables (stays the same) int x = 0; int speed = 1; // Setup does not change void setup() { size(200,200); smooth(); } void draw() { background(255); move(); // Instead of writing out all the code in draw(), we simply call three functions. bounce(); display(); } // Where should functions be placed? // You can define your functions anywhere in the code outside of setup() and draw(). // However, the convention is to place your function definitions below draw(). // Declare functions below draw() // A function to move the ball void move() { // Change the x location by speed x = x + speed; } // A function to bounce the ball void bounce() { // If we have reached an edge, reverse speed if ((x > width) || (x < 0)) { speed = speed * - 1; } // A function to display the ball void display() { stroke(0); fill(175); ellipse(x,100,32,32); }

Another great benefit functions have is the ease of debugging. We can simply turn off, by commenting out, parts of the program to determine if that particular function is working properly. void draw(){ background(0); // move(); // bounce(0); display(); } By adding function calls one by one and executing the sketch each time, we can more easily deduce the location of the problematic code. 14

see web notes for example 15

What if you wanted to use a function to do slightly different things? Some examples you have seen pass arguments to functions such as: 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? See example: 16

/* this will take different arguments for color and size and send to function makecircle*/ void setup(){ size (500, 500); smooth(); } void draw(){ background(255); drawCircle(?, ?, ?, ?, ?); // fill in the arguments: color is a hexidecimal or 8 bit grey value //make other versions of the elllipse } //function definition void drawCircle(int x, int y, int itsWidth, int itsHeight, color c){ fill (c); ellipse (x,y, itsWidth, itsHeight); } /*once you have created a single ellipse use the function over and over again to create more ellipses but with difference */ 17

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 18

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 } 19

void draw() { int answer; (5)answer = (1) sum( 17, 42, 52 ); println(answer); noLoop(); } (2) int sum(int a, int b, int c) { int total = a + b + c; (3) return total; (4) } draw calls sum with arguments 2. sum receives values into parameters 3. sum method calculates local total 4. sum method returns copy of total 5. draw assigns returned value to answer

21 /* write your own function that calculates sales tax*/ // define global variable float yourCharge; void setup(){ yourCharge = tax( 1.00, 3.00, 5.00); // calls tax function and passes arguments to function println ("Your total charge is = " + yourCharge); } // define function for sales tax///////////// float tax( float a, float b, float c){ // receives the arguments and runs the method to solve float subtotal = a + b + c; // total items cost float taxRate =.0625; // tax rate float tax = subtotal * taxRate; //total tax amount needed float totalCharge = subtotal + tax; return totalCharge; } You write the function using above info.

 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 Smith22