Variables One More (but not the last) Time with feeling

Similar documents
Notes from the Boards Set # 5 Page

We will start our journey into Processing with creating static images using commands available in Processing:

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Pick a number. Conditionals. Boolean Logic Relational Expressions Logical Operators Numerical Representation Binary. CS Conditionals 1

CISC 1600 Lecture 3.1 Introduction to Processing

Bits and Bytes. How do computers compute?

Basic Computer Programming (Processing)

[ the academy_of_code] Senior Beginners

1 Getting started with Processing

CISC 1600, Lab 2.1: Processing

What can we do with Processing? Let s check. Natural Language and Dialogue Systems Lab Guest Image. Remember how colors work.

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2

What is a variable? A named locajon in the computer s memory. A variable stores values

What is a variable? a named location in the computer s memory. mousex mousey. width height. fontcolor. username

Processing Assignment Write- Ups

Module 01 Processing Recap. CS 106 Winter 2018

Introduction to Processing

CISC 1600, Lab 3.1: Processing

Module 01 Processing Recap

if / if else statements

CIS 110 Introduction to Computer Programming Summer 2014 Midterm. Name:

The Junior Woodchuck Manuel of Processing Programming for Android Devices

1 Getting started with Processing

Lecture 7. Processing Development Environment (or PDE)

Appendix: Common Errors

mith College Computer Science CSC103 How Computers Work Week 7 Fall 2017 Dominique Thiébaut

Repetition. We might start out with the following program that draws only the left most object.

Old 257 Exam #2s for Practice

CS110 Introduction to Computing Fall 2016 Practice Exam 1 -- Solutions

CST112 Looping Statements Page 1

CSE120 Wi18 Final Review

Kimberly Nguyen Professor Oliehoek Introduction to Programming 8 September 2013

mith College Computer Science CSC103 How Computers Work Week 6 Fall 2017 Dominique Thiébaut

Art, Randomness, and Functions

CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation. Warm-up. Stretch

Miscellaneous Stuff That Might Be Important.

CISC 1600, Lab 2.2: Interactivity in Processing

Using Methods. Writing your own methods. Dr. Siobhán Drohan Mairead Meagher. Produced by: Department of Computing and Mathematics

Transcriber(s): Aboelnaga, Eman Verifier(s): Yedman, Madeline Date Transcribed: Fall 2010 Page: 1 of 9

The way I feel about music is that there is no right and wrong. Only true and false. Fiona Apple. true false false

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

ASSIGNMENT 2. COMP-202A, Fall 2013, All Sections. Due: October 20 th, 2013 (23:59)

Watch the following for more announcements

Question 2. [5 points] Given the following symbolic constant definition

CISC 1600, Lab 3.2: Interactivity in Processing

COMP Summer 2015 (A01) Jim (James) Young jimyoung.ca

Interaction Design A.A. 2017/2018

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Computer Science is...

Notes from the Boards Set BN19 Page

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Interaction Design A.A. 2017/2018

Class Notes CN19 Class PImage Page

Last class. -More on polymorphism -super -Introduction to interfaces

Introduction to Game Programming Lesson 4 Lecture Notes

Chapter 4 Introduction to Control Statements

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Variables and Control Structures. CS 110 Eric Eaton

An Introduction to Processing

Repetition is the reality and the seriousness of life. Soren Kierkegaard

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14

Using Flash Animation Basics

Animations involving numbers

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Chapter 2 Exercise Solutions

Unit 1 Lesson 4. Introduction to Control Statements

Fast Introduction to Object Oriented Programming and C++

1. Complete these exercises to practice creating user functions in small sketches.

Lab 12: Lijnenspel revisited

Prof. Carl Schultheiss MS, PE. CLASS NOTES Lecture 12

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

CS110 Introduction to Computing Fall 2016 Practice Exam 1

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Expressions and Casting

CSE 142/143 Unofficial Style Guide

CS 177 Recitation. Week 8 Methods

do fifty-two: An Introductory Programming Language

Recall that creating or declaring a variable can be done as follows:

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

Smoother Graphics Taking Control of Painting the Screen

Defining Classes and Methods

Load your files from the end of Lab A, since these will be your starting point.

Instructor (Mehran Sahami)

Question 1 (10 points) Write the correct answer in each of the following: a) Write a Processing command to create a canvas of 400x300 pixels:

JAVA GUI PROGRAMMING REVISION TOUR III

CpSc 1111 Lab 4 Formatting and Flow Control

6 Stephanie Well. It s six, because there s six towers.

Programming Project 1

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Class #1. introduction, functions, variables, conditionals

CS 101 Computer Science I Fall Instructor Muller. stddraw API. (DRAFT of 1/15/2013)

Intro. Speed V Growth

CS Week 13. Jim Williams, PhD

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

A B C D CS105 03a Interaction

Design Programming DECO2011

CISC 1600, Lab 2.3: Processing animation, objects, and arrays

Transcription:

1 One More (but not the last) Time with feeling All variables have the following in common: a name a type ( int, float, ) a value an owner We can describe variables in terms of: who owns them ( Processing or us ) who declares them who initializes them who changes them who can use them how long the actually live during the execution of our program. Here is what we have talked about thus far: Item System Global Who owns Processing We do Who declares Processing We do Who initializes Processing Processing to a default initial value: int to zero float to zero.zero char to a null character boolean to false If these values are not useful to us, we have to initialize the variable to values that are useful and we should do this in the setup( ) function. Who changes Processing We do Who can use Both Processing and us We do

2 How long do they live? As long as the program is running As long as the program is running We need to expand this list with two additional categories: function definition arguments and local variables. We have to do this because you can get into trouble (your code will not run ) through no fault of your own (until you read this ). Some of you may have already hit this problem. From the past: System variables are just that variables maintained by Processing. We can use them but the code that declares and initializes them is hidden from us. Global variables are declared in our code and must be outside any visible set of braces. The following code has four global variables marked in red: int i; fill( 0 ); float f; rect( 0, 0, width, height) ; char c; void keypressed( ) println( "Value of variable i is " + i ); println( "Value of variable f is " + f ); println( "Value of variable c is " + c ); println( "Value of variable b is " + b ); boolean b; Global variables do not have to be declared at the top of the code but for 15-102, we prefer that you do declare them at the top. It makes helping you easier for us. The code above produces this output:

3 Value of variable i is 0 Value of variable f is 0.0 Value of variable c is Value of variable b is false The four global variables are named i, f, c, and b. They are global because they are declared outside the braces of the three function definitions. Note the initial values provided by Processing. The char (short for character) variable is initialized to a special null character that does not print anything so we do not see it. Word put the red box in this document to indicate that something is there. Function Definition Arguments are similar to system and global variables in that they have a name, type, value, and an owner. The differences between the function argument and the system and global variables can be seen in the other items in our list: Item Who o wns Who declares Who initializes Who changes Who can use How long do they live? System Global Function Definition Arguments Processing We do The function does Processing We do The function does in the function s header Processing Processing to a defined Processing initializes initial value: them by copying t he int to zero value of the argument float to zero.zero in the function call char to space into the function boolean to false definition argument. If these values are not useful to us, we have to initialize t he variable Processing We do Only this function can change them. Both Processing We do Only this function can and us use them. As long as the program is running As long as the program is running Only as long as the function is being executed by Processing. When the execution of the function is complete, the memory used by the argument is returned to the operating system for reuse.

4 It is very important to remember two things: 1. The initial value comes from the argument in the function call 2. The argument exists only while the function is being executed. Local variables are very similar to function definition arguments. Once again, we return to our list to find the differences: Item Who o wns Who declares Who initializes Who changes Who can use How long do they live? System Global Function Definition Local Arguments Processing We do The function does The function does Processing We do The function does in the function s header Processing Processing to a defined initial value: int to zero float to zero.zero char to space boolean to false If these values are not useful to us, we have to initialize t he variable Processing initializes t hem by copying the value of the parameter in the call into the function argument. Processing We do Only this function can change t his argument Both Processing and us As long as the program is running We do As long as the program is running Only this function can use this argument Only as long as the function is being executed by Processing. When the execution of the function is complete, the memory used by the argument is returned to the operating system for reuse. We do bet ween the braces of the function We have to. If we do not initialize them before we attempt to use them, Processing will not compile our code Only this function can change this local variable Only this function can use this local variable Only as long as the function is being executed by Processing. When the execution of the function is complete, the memory used by the argument is returned to the operating system for reuse. If we declare a variable within the braces of a function, that variable is a local variable. This point is very important. Forgetting it can cost you a great deal of time.

5 Here is how forgetting this can get you into trouble: int x, y, wd, ht; fill( 0 ); int x = 100; int y = 50; int wd = 15; int ht = 10; rect( x, y, wd, ht) ; println( x + " " + y + " " + wd + " " + ht ); This code compiles and runs and produces this output in the window: We are expecting to see a black rectangle located 100 pixels to the right, 50 pixels down with a width of 15 pixels and an height of 10 pixels. But we see nothing. A clue comes from the println( ) function call. Here is what we see in the console window:

6 The values of the global variables are all zero. So what happened??? int x, y, wd, ht; fill( 0 ); int x = 100; int y = 50; int wd = 15; int ht = 10; rect( x, y, wd, ht) ; println( x + " " + y + " " + wd + " " + ht ); Let s return to the code. Look at the setup( ) function. The four lines with red text are variable declarations. Any time you see: or data-type variable-name; data-type variable-name = some-value; You are looking at a variable declaration. Since the four lines with red text are within the braces of the setup( ) function, they are declaring local variables owned by the setup function. At this point in the execution of the program, there are eight variables: four global variables named x, y, wd, ht four local variables named x, y, wd, and ht Processing is very comfortable with this situation. It works with the local variables if they exist. This code alters the values of the four local variables and does

7 not do anything with the global variables. Their values remain unchanged so they are zero. One very important thing to remember is this row from our comparison grid: Item How long do they live? System As long as the program is running Global As long as the program is running Function Definition Arguments Only as long as the function is being executed by Processing. When t he execution of the function is complete, the memory used by the argument is returned to the operating system for reuse. Local Only as long as the function is being executed by Processing. When t he execution of the function is complete, the memory used by t he argument is returned to the operating system for reuse. These four local variables exist only as long as it takes Processing to execute all of the stuff our code requires it to execute in the setup( ) function. Once the setup( ) function is finished, the four local variables, x, y, wd, and ht are destroyed leaving only the four unchanged global variables. The code shown above can be fixed by removing the type name float from the four lines of code that are attempting to initialize the variables: int x, y, wd, ht; fill( 0 ); x = 100; y = 50; wd = 15; ht = 10;...

8 This is very subtle and you need to be aware of it. We will revisit these ideas again in the course. When do I use a local variable and when do I use a global variable? Part of the answer is rather easy to explain: If the value of the variable is needed in more than one function, it probably should be a global variable. This part is not that simple: For some cases, if the value of the variable is used only within one function, it can be a local variable. The fuzzy part gets into efficiency. In an intro course, we usually do not worry about efficiency. However, we are not a typical intro course. We will do some animation and if we are not careful, we can write code that does not allow for smooth, fast, pleasant animation. Jim will show you an example of this in class. The processor in the computer can only do so much in a finite amount of time. Processing has a default frame rate of 60 frames per second. This rate is possible only if the processor can do all we tell it to in a slice of time that is 1/60 th of a second or less. If we tell it to do more than it can accomplish in 1/60 th of a second, the animation rate slows down. Each line of code takes time. If we can eliminate a line of code, we reduce the amount of work the processor has to do in the 1/60 th of a second for each frame and it can contribute to a smoother, more pleasant animation.

9 Suppose we have a function that computes the same value repeatedly for each animation: ellipse( width/2, height/2, framecount%width, framecount%height); In this example, the code draws an ellipse that grows from a very small circle to a large circle. The maximum diameter is the width or height of the window (the window is square). The circle is always located at the center of the circle so the two arguments in green evaluate to the same value for every execution of the draw( ) function. However, since the value of framecount changes for each execution of the draw() function, the values of the blue arguments are constantly changing. We could save some execution time for each execution of the draw() function if we declared global variables that store the values of half of the width and half of the height. Note that we could not measure the time we are saving in this simple example but we would safe a very small fraction of a second. int halfwidth, halfheight; fill( 255 ); halfwidth = width/2; halfheight = height/2; ellipse( halfwidth, halfheight, framecount%width, framecount%height);

10 As you write your code, you should begin to develop an eye for redundant or unneeded code. Here is a common novice example: background( 0 ); smooth( ); fill( 255, 0, 0 ); rect( framecount%width, height/2, width*.1, height*.2 ); There are a number of redundant or unneeded lines of code in the draw() function. See if you can find them before reading further

11 Every execution of draw( ) does this: background( 0 ); smooth( ); fill( 255, 0, 0 ); rect( framecount%width, height/2, width*.1, height*.2 ); This is a better way to code draw( ): background( 0 ); rect( framecount%width, halfheight, rectwidth, rectheight ); The smooth() function needs to be called only one time do this in setup(); Since there is only one rect and it is always filled with red, fill( ) needs to be called only one time. - do this in setup(); If there are multiple rects or ellipses of different color, this strategy will not work. Declare global variables and initialze them in setup() to be half of the height, 10% of the width and 20% of the height. int halfheight; float rectwidth, rectheight; fill( 255 ); halfheight = height/2; rectwidth =.1*width; rectheight =.2*height; background( 0 ); smooth( ); fill( 255, 0, 0 ); rect( framecount%width, halfheight, rectwidth, rectheight);

12 This type of coding may never affect your code but it makes your code much easier to read and edit. Declaring functions that are not void in our code: Thus far we have written only void functions. Many of you asked what void meant. We told you that it meant that the function returns nothing. Not a very satisfying answer. Maybe we can add more depth to that answer. Here is the structure of a function definition: return type name open-paren argument-list close-paren open-brace stuff-to-do close-brace and an example void drawinitials( int x, int y, int wd, int ht) fill( 0 );... The function drawinitials( ) returns no values that the program can use. It draws our initials. So we say that since it returns no values, it is a void function. Here is another function definition: int doubleargumentvalue( int number) return number*2; We would probably never write this as a function since doubling the value of a variable is very easy just multiply it by 2. But it does show how we can define a function to compute and return the value computed.

13 The call could look like any of these: text( doubleargumentvalue ( 42, 100, 100 ) ); or int x = 42; int doublex = doubleargumentvalue( x ); or int x = 42; int y = 24; rect( doubleargumentvaule( x ), doubleargumentvaule( y ), x, y ); Using functions like this is ideal for complex arithmetic expressions that are used multiple times in your code. Write the expression one time in a function and call the function where you need the value. Another advantage is that if you find that you coded the expression incorrectly, you only have to make a single correction.