Functions. functions: a collection of lines of code with a name that one can call. Functions can have inputs and outputs.

Slides:



Advertisements
Similar presentations
First of all – lets look at the windows you are going to use. At the top you have a toolbar, with all your various tools you can use when customising your.
Advertisements

Noadswood Science,  To understand the flow procedure when writing programs Thursday, January 15, 2015.
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Exponential Functions Logarithmic Functions
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Chapter 16 Recursion: Another Control Mechanism. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. a.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Computer Science 1620 Loops.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
, Fall 2006IAT 800 Lab 2: Polygons, Transformations, and Arrays.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Introduction to TouchDevelop
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
What is Scratch? Scratch as Logo Dr. Ben Schafer Department of Computer Science University of Northern Iowa.
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
RECURSION Recursion Towers of Hanoi To Recurse or to Loop? Fractals Do something!
Log on and Download from website:
by Chris Brown under Prof. Susan Rodger Duke University June 2012
In.  This presentation will only make sense if you view it in presentation mode (hit F5). If you don’t do that there will be multiple slides that are.
Introduction to Scratch!
Week 11 DO NOW QUESTIONS. An ask turtles block is a set of instructions that is issued to every turtle. Even though computers can do things very quickly,
Functions and subroutines – Computer and Programming.
“Teach A Level Maths” Vol. 1: AS Core Modules
Graphics and Procedures Programming Right from the Start with Visual Basic.NET 1/e 5.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1 Loops and Branches Ch 21 and Ch18 And how you can use them to draw cool pictures!
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Hopefully this lesson will give you an inception of what recursion is.
CSC Intro. to Computing Lecture 13: PALGO. Announcements Midterm is in one week  Time to start reviewing  We will do more review in class Tuesday.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Art 321 Lecture 7 Dr. J. Parker. Programming In order to ‘make things happen’ on a computer, you really have to program it. Programming is not hard and.
Introduction to TouchDevelop
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
1 Building Your Own Turtle Functions For making really cool pictures!
Loops & Graphics IP 10 Mr. Mellesmoen Recall Earlier we wrote a program listing numbers from 1 – 24 i=1 start: TextWindow.WriteLine(i) i=i+1 If.
Recursion Pepper. Another way to loop Call yourself repeatedly until you say to stop. Example: add up 10 numbers using addUp. -- Input – number to count.
1/37 Andries van Dam  /27/15 Lecture 14 Recursion.
1 Project designed and created by M. Shajith Kumar.
1 Building Your Own Turtle Functions For making really cool pictures!
Getting started with the turtle Find the latest version of this document at
 Make sure you are subscribed to announcements on Moodle.  Activity 5 will be due before the beginning of lab next week.  Check Moodle for complete.
Comments, Conditional Statements Continued, and Loops Engineering 1D04, Teaching Session 4.
Programming Training kiddo Main Points: - Python Statements - Problems with selections.
Algorithms and Pseudocode
Fractal Art. What is Fractal Art? A fractal is a geometric shape that has self similarity, that is it can be split into pieces that are approximate reduced.
First of all – lets look at the window’s you are going to use. At the top you have a toolbar, with all your various tools you can use when customising.
Turtle Graphics Lesson 2 1. There are 3 homeworks to complete during the six lessons of this unit. Your teacher will let you know when a homework has.
Conditionals.
LOGO WHAT IS IT? HOW TO USE IT AND HOW USEFUL CAN IT BE?
For loops. turtle drawings – common core state standards 1.1 Innovate: Demonstrate creative thinking, construct knowledge and develop innovative products.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Functions. functions – learning targets I will be able to understand how to trace function I will be able to learn how to lavage inputs and outputs with.
Using the Python Turtle
Stage 3: Artist What do you remember from the last class?
Math operations 9/19/16.
Week 3 DO NOW QUESTIONS.
FLOWCHARTS Part 1.
LOGO BY Kaotip 9S.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Exercise (1) What does function chai draw? def chai(size):
CISC101 Reminders Quiz 2 this week.
Introduction to TouchDevelop
Looping Topic 4.
Recursion Taken from notes by Dr. Neil Moore
Mod 2 Lesson 2 Repeating with loops
Lesson Six Drawing.
Presentation transcript:

functions

functions: a collection of lines of code with a name that one can call. Functions can have inputs and outputs.

functions o Functions are sub-scripts that let you write more complicated programs. o Anything that can happen in normal code can happen in a function. o However, variables are generally not shared across functions

practice o Write a function that draws an equilateral triangle, then call it from the main portion of your program. o If you finish, try coming up with ways to call the function multiple times

parameters o One powerful way to use functions is to add parameters. o These are variables that are passed between the caller and the function, and let the function act in different ways.

inputs o inputs are the values passed when calling a function. (‘params’ tab in app) action sum(x : Number, y : Number) z := x + y z->post to wall “x” is an input “x” is a number “y” is also a number input you can use inputs in the function. They already exist when you enter the function.

inputs o What will main do? action main code->sum(1, 2) code->sum(5, 7) action sum(x : Number, y : Number) z := x + y z->post to wall

outputs o Outputs are the values returned when leaving a function. (‘returns’ tab in app) action sum(x : Number, y : Number) return r : Number r := x + y “r” is an output “r” is a number we assign the value to the output. This will be the value returned by sum

outputs o What will main do? action main var z := code->sum(4, 3) z->post to wall action sum(x : Number, y : Number) returns r : Number r := x + y

exercise 1 o write an action that computes the sum of 3 numbers and posts it to the wall. o write an action that returns the sum of 3 numbers

exercise 2 o write an action that takes a “length” number and draws a pentagon using that length o add a parameter for the color and draw the triangle with that color

recursion an function that calls itself…

square o Start by drawing a square using a function called square. o We’ll add recursion to this on the next slide.

square recursive private action square(side : Number, depth: Number) for 0 <= i < 4 do turtle->forward(side) turtle->left turn(90) if depth > 0 then ▷ square(side * 0.4, depth – 1) action main turtle->initialize ▷ square (200, 4) recursion! square calls itself

squares recursive action square(length : Number, depth : Number) for 0 <= i < 4 do turtle->forward(length) turtle->turn(90) if depth > 0 then ▷ square(length * 0.4, d – 1) action main turtle->initialize ▷ square(200, 4) recursion! square calls itself smaller square going deeper into the fractal

tree – first step 1. Move forward side 2. Turn left 20 degrees 3. Move forward side * Move backwards side * Turn right 40 degrees 6. Forward side * Backwards side * Left 20 degrees 9. Backwards side

tree – first step Private action tree(side : Number, depth: Number) turtle->forward(side) turtle->left turn(20) turtle->forward(side*0.8) turtle->forward(-side*0.8) turtle->right turn(40) turtle->forward(side*0.8) turtle->forward(-side*0.8) turtle->left turn(20) turtle->forward(-side)

how do we add recursion? o Do we want to add it at the end? o At the beginning? o Maybe we want to replace some aspect of the program we’ve already written?

adding recursion Try replacing the 2 lines below with recursion (in the tree action): turtle-> move(side*0.8) turtle-> move(-side*0.8)

branches o Let’s draw a branch… how do you draw this? 1: forward c 2: right turn 45 3: forward c/2 4:forward –c/2 5: left turn 45 6: left turn 45 7: forward c/2 8: forward –c/2 9: right turn 45 10: forward -c

branch action action branch(c : Number) // go to trunk turtle->forward(c) // rotate towards right branch turtle->right turn(45) // move to tip of the right branch turtle->forward(c/2) // go back to the top of trunk turtle->forward(-c/2) // cancel right turn turtle->left turn(45) // rotate towards left branch turtle->left turn(45) // move to tip of the left branch turtle->forward(c/2) // go back to the top of the trunk turtle->forward(-c/2) // cancel right turn turtle->left turn(45) // go back to base turtle->forward(-c)

branch becomes tree

tree action action branch(c : Number, d : Number) // go to trunk turtle->forward(c) // rotate towards right branch turtle->right turn(45) // move to tip of the right branch turtle->forward(c/2) if d > 0 then branch(c * 0.4, d – 1) // go back to the top of trunk turtle->forward(-c/2) // cancel right turn turtle->left turn(45) // rotate towards left branch turtle->left turn(45) // move to tip of the left branch turtle->forward(c/2) if d > 0 then branch(c * 0.4, d – 1) // go back to the top of the trunk turtle->forward(-c/2) // cancel right turn turtle->left turn(45) // go back to base turtle->forward(-c)

exercises o change the thickness of the trunk and branches based on the depth – it should get thinner as you draw deeper the branches o change the color from brown (top level) to green (deepest level) o instead of 2 child branches, use 4 child branches (tip: use a for loop). o add small random variations to the turns and moves to make the tree look more ‘natural’.

turtle exercise o Write a program that draws a square. Use a variable to represent the side length. o Once you’re done, choose a random color and a different pen thickness for each side. o You can also try drawing other shapes

practice o Go back and add a parameter for side length to your triangle function. o Try calling your function with different values for that parameter.

experiment o There are lots of cool geometric drawings you can make with turtle. Here are a few ideas to get you started: o Use functions within a loop so that they get called many times. o Draw circles, diamonds, or stars. o Try functions that don’t return the turtle to where it started.

circle o solution: “create a turtle program that draws a circle” turtle→initialize for 0 <= i < 360 do turtle→move(1) turtle→turn(1)

exercise o Write an app that draws a circle using twenty sides. o Make sure to use a variable to represent side length – you may be surprised to see how big or small your circle will be

question o What does this do? for 0 <= i < 100 do i→post to wall

exercise 0 o Write an app that prints the squares of the numbers 0 through 100 to the wall Too easy? Try writing an app that finds the sum of those numbers instead.

exercise 1 o start a new turtle script o create an new action, named ‘triangle’, that draws a triangle of length 200 action triangle() for 0 ≤ x forward(200) turtle->left turn(120) o in ‘main’, create a ‘for loop’ that calls the ‘triangle’ action 100 times turtle->initialize for 0 ≤ x triangle o after each ‘triangle’ call, rotate the turtle by 5 degrees turtle->initialize for 0 ≤ x triangle turtle->left turn(5)

exercise 2 o change the ‘triangle’ action to take the side length as an input, use that length when drawing the triangle action triangle (length : Number) for 0 ≤ x forward(length) turtle->left turn(120) o in main, when calling ‘triangle’ in the for loop, increase the length by 5 per iteration var length := 20 for 0 ≤ x triangle(length) turtle->left turn(5) length := length + 5

exercise 3 o change ‘triangle’ to take the side color as an input o in ‘main’, when calling ‘triangle’, use a random color

exercise 4 o change ‘triangle’ to take the side thickness as an input. The unit of thickness is pixels. o in ‘main’, when calling ‘triangle’, increase the thickness on each iteration

exercise 5 o change ‘triangle’ to take the number of sides as an input. For a triangle, #sides is 3, for a square #sides is 4, etc… o in ‘main’, increase the number of sides of the polygon being drawn on the screen on each iteration.

o recreate the following turtle drawing

o start by creating an action that draws a line of gears o then use it in a loop… o think like a turtle

inputs/outputs action sum(x : Number, y : Number) return r : Number r := x + y “x” is an “number” input “y” is a “number” input “r” is an “number” output. Its value is what the function returns.

action sub(x : Number, y : Number) returns r : Number r := x – y action add(x : Number, y : Number) returns r : Number r := x + y action ex1() var z := code->sub(10, 5) z->post to wall action ex2() var z := code->add(10, 5) z := code->sub(z, 6) z->post to wall action ex3() var z := code->sub(code->add(1, 2), code->add(4, -1)) z->post to wall What does ex1, ex2, ex3 do?

var z := code->sub(code->add(1, 2), code->add(4, -1)) Always process the inner expressions first... We evaluate the first code->add call. var z := code->sub(3, code->add(4, -1)) Then the 2 nd add call var z := code->sub(3, 3) and finally, the call to ‘sub’ var z := 0

last turtle once you are done with the basic shape, add your own colors/mods/customizations publish your script so that we can demo it to the class!

recursion Writing a function that calls itself

sum sum 1 to 2 = sum 1 to 3 = = (sum 1 to 2) + 3 sum 1 to 4 = = (sum 1 to 3) + 4 sum 1 to 5 = _____________ = (sum 1 to __) + ___ sum 1 to 6 = _____________ = (sum 1 to __) + ___ Now let’s say n is any positive number sum 1 to n = … + n – 1 + n= (sum 1 to ___) + ____

factorial factorial(n) = n! = 1 * 2 * … * n 1! = ____________ 2! = ____________ = _____ ! * _______ 3! = ____________ = _____ ! * _______ 4! = ____________ = _____ ! * _______ Now let’s say n is any positive number, n! = ____________ = _____ ! * _______

what is recursion? o Recursion is when a action calls itself o Here’s an example that calculates sum 1 to n: action sum(n : Number) returns r : Number if n = 1 then r := 1 else r := n + code->sum(n-1)

recursion is awesome o Recursion lets you write extremely complicated programs succinctly o Recursion lets you write programs that would be nearly impossible otherwise o Recursion is an awesome concept once you really understand it

recursion is hard o Keeping track of what a recursive function does is confusing o Writing functions that work at multiple levels of recursion is challenging o Infinite recursion can crash your program Look at the sum function from a few slides ago. What happens when n = 0?

factorial o Try changing your program to calculate n factorial instead of the sum of the numbers up to n. o Remember n factorial, or n!, is equal to 1 * 2 * … * n