# Functions, and More Functions

Hello everyone! I am sharing my lessons for introducing functions with middle school students. I have been out of the classroom an awful lot during April, so this has meant I often had to leave video lessons when I might have preferred having the students do inquiry. There’s a lot more that could be done to turn these lessons into rich tasks. I hope you share what you do with them!

The concept of a function in computer science is similar to, but not completely identical to, the function you learn about in math class.

In mathematics, a function is a rule you apply to one or more inputs. You get exactly one unique output.

In computer science, a function is a rule you apply to ZERO or more inputs. You can get no outputs or any output you want from a single unique number to a boolean value to a text string to an entire data structure.

In general, the reason you use a function in computer science is to make a chunk of code re-usable. For example, if you’re creating a video game, you might have 100 lines of code that render a character in your game. Instead of copying and pasting the 100 lines each time you draw the character, you can simply write:

drawMainCharacter(x,y);

and your main character will appear at coordinates (x,y) on the screen.

This year, I used an awful lot of direct instruction to teach students about functions. I would have liked to make it more inquiry based. 1) I don’t fully know how yet and 2) I’ve been out of the classroom enough that I had to make flipped lessons that could be used as sub plans. This is what I did.

Day 1: Introduction to Functions. I had my students start with this program here, which draws a simple cat face with 23 or so lines of code.

I have them turn it into a program that draws a kitty, then one that draws a kitty at a random location, and then one that draws a kitty at a random location with a specified head size.

Students figure out from each other how to add random coloring of the kitty, and then how to make lots and lots of them. If I have a class in which kids have already done some Khan Academy programming lessons, often they’ll know how to use the draw() loop to animate lots of kitties, and productive chaos ensues as they teach each other how to do this. Programming suddenly starts to become really fun.

I have always struggled with the “I-do / You-do / We all do” mode of teaching students how to do something. And when I’m teaching a new programming structure, sometimes there is just something to typing in a canned program.

Day 2: Special functions. A common paradigm for video game programming is to have functions that are set up to run as infinite loops. In many environments, you’ll see an update() and a draw() function. These run over and over and over again, many frames per second. The functions change variables in your game and then re-draw the screen according to the information in the variables. Part of the work of game design is figuring out what information you have to manage and change each frame. I start on functions before I even do loops because you get so much reward out of the built-in animation and interactive-ness brought to you through these functions.

In Khan Academy, a couple of special functions are:

```var draw = function()
{```
`};`

This function will execute about 60 times per second. It’s the main animation loop in the Processing language, which this JavaScript implementation uses. You use it to update variables and then re-draw your screen. draw() takes no inputs and has no outputs.

```var mouseClicked = function()
{```
`};`

This special function is executed anytime the mouse button is clicked (that is, pressed and then released). Again, there are no inputs and no outputs.

In both of these functions, you can make use of special variables: mouseX and mouseY. These variables, at any point in your program, contain the x and y coordinates of your mouse.

I chose to use a little video lesson to introduce the purposes of these functions by animating a little stick man.

http://screencast-o-matic.com/watch/cofib8e9c3

Here is the starter that simply draws a stickman.

Day 3: Gravity and Bouncing

Once students learn how to animate the stickman, they’re always interested in learning how to make the character bounce, or how to add a gravity jump! In this task, as with many computer science tasks, the challenge is not in how to implement it but how to plan it. You need to understand what variables you’re working with and how they change with each frame of the animation.

What do I normally do when I plan an animation? I consider the rules that govern the movement of the characters. What changes? What mathematical rules decide the change?

I gave the students a planning sheet with a crude 400×400 coordinate grid (remember, 0,0 is in the upper left) and a T-chart. With the t-chart, they could plan the position of a bouncing character.

The x-coordinate and the change in the x coordinate both need to be variables.

The T-chart shows that the x-coordinate is changing by adding 20 to its value up until it reaches the coordinate 400, and then it changes by adding -20. The x-coordinate and the speed both need to be variables, and the rule for changing the speed from positive to negative is that when the x-coordinate is greater than or equal to 400, the xspeed value is changed by multiplying it by -1.

All of this functionality goes in the draw() function that runs over and over again, at about 60 frames per second.

The same logic can be applied to the y-coordinate. The final result is here, and it uses two functions: stickman() and draw().

Stickman Bounce Program

Then we got to planning for a gravity jump. In a gravity jump, your stickman makes a parabola shape, which some students had already learned about a little in Algebra II.  You can plan for the motion using a graph and a T-chart.

By the way, I really do this when I am planning an animation. Most of it is done in my head at this point, but when I was an early programmer, I did a lot of this type of sketching out and planning.

The x-coordinate changes linearly, but the y-coordinate has a different pattern.

In this case, the x-coordinate goes up in a linear fashion but the y-coordinate change is more interesting. The y-coordinate changes by a different amount every frame, but the *change* in the y-coordinate is what changes in a linear fashion.  It’ll increase by -60, then -40, then -20, and so on until it has gotten back to the y-coordinate of 360 or higher.

This is what that program looks like in action. I played with the initial speed and the force of gravity until the jump seemed a little realistic.

Stickman Gravity Jump

I made a video lesson about this process since I was absent the day the lesson was taught. I don’t think my students could reproduce it. I suppose my learning goal was for them to appreciate the planning process and to understand how to use the draw() and mouseClicked() functions in an animation.

http://screencast-o-matic.com/watch/cofoejeSrL

Day 4: Function Return statements and Money Program

I had students work on the video lessons about functions in Khan Academy and learn about function return values.  They started with the first lesson and ended up at the Calculator activity. I was gone for this class (I was out so much in April!)

Their independent task was to finish this “moneyface” program.

```var pennies = 1468;
var nickels = 486;
var dimes = 400;
var quarters = 361;
var dollars = 330;

var rich = totalMoney(dollars, quarters, dimes, nickels, pennies);

face(rich);```

The code uses two functions, totalMoney() and face().  I asked for totalMoney() to take five inputs as shown, and have a return value that would be the total amount of money you have. The face() function should draw a happy face if you had more than 500 dollars, otherwise a sad face.

Some students were able to complete the task, but I could tell others were not quite there when it came to function return values. This is what the final program should look like.

MoneyFace Program

Day 5: Matching Activity and finish money face program

When I looked at student work, I could tell they needed more support with writing functions, so I created a matching activity. In the activity, I give them a diagram showing inputs and outputs of a function, a function definition, and a function call. They have to match the three faces of a function together.  This Google Doc shows the matches side by side.  I cut the document up into cards and gave each team a set of cards.

Function Matching Cards

This activity was engaging and challenging and it really went very well. Many students told me they really felt they understood functions a lot better, so it was a helpful activity. Afterward, I helped different groups finish their “money face” program while the ones who were done were able to start watching videos on While loops.

If I did this unit again, I would have brought out the matching activity a lot sooner and would have really restructured the gravity and bouncing activities. I know the students *saw* how I interact with planning an animation, but I don’t think it helped them plan an animation. You learn these things as you need them, and the need wasn’t really there for the students.  If they didn’t come into the activity with a curiosity about how it worked, the activity wasn’t going to stick. Next year I’ll decouple the bouncing and gravity math from the learning of functions and work on it during the final project time.

I'm a former software engineer who has taught middle school math and computer science for the past 6 years. I believe every kid has the right to be a thinker. I started this blog to save resources for integrating programming in the Common Core math classroom. I also use it to save my lessons and reflections from teaching budding computer scientists! Coding has transformed how I teach and think. You'll love what it does for you. You should try it.

### 2 responses to “Functions, and More Functions”

1. A comment on direct instruction vs discovery. These days it seems that “direct instruction” is a dirty word when in fact many times it’s necessary and appropriate.

Discovery is great when you can set it up and guide it but just like direct instruction, it’s just a tool in the belt. Sometimes it’s great but sometimes you get more bang for your buck with traditional lecturing.

Remember, in the history of mankind the discovery method only led to 2 people coming up with calculus.

• dupriestmath says :

Sorry for not replying sooner. I hear what you’re saying. Perhaps the disconnect I’m seeing is that I give direct instruction before the students really have a need to know. I need to create the need first and maybe that is best done with discovery.