Variables and Control Structures. CS 110 Eric Eaton

Similar documents
Evaluating Logical Expressions

void mouseclicked() { // Called when the mouse is pressed and released // at the same mouse position }

Condi(onals and Loops

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

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

A B C D CS105 03a Interaction

Exploring Processing

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

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

1 Getting started with Processing

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

Watch the following for more announcements

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

Bits and Bytes. How do computers compute?

5.1. Examples: Going beyond Sequence

Computer Graphics. Interaction

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

Sten-SLATE ESP. Graphical Interface

Introduction to Processing. Sally Kong

CISC 1600, Lab 2.2: Interactivity in Processing

CISC 1600, Lab 3.2: Interactivity in Processing

Module 01 Processing Recap. CS 106 Winter 2018

Kimberly Nguyen Professor Oliehoek Introduction to Programming 8 September 2013

CST112 Variables Page 1

CISC 1600 Lecture 2.2 Interactivity&animation in Processing

Basic Computer Programming (Processing)

INTRODUCTION TO PROCESSING. Alark Joshi, Amit Jain, Jyh-haw Yeh and Tim Andersen

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

if / if else statements

Class #1. introduction, functions, variables, conditionals

CISC 1600 Lecture 2.2 Interactivity&animation in Processing

CST112 Looping Statements Page 1

Miscellaneous Stuff That Might Be Important.

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

Introduction to Processing

Conditional Events. Mouse events and Operators. Dr. Siobhán Drohan Mairead Meagher. Produced by:

Review. Custom Objects. Comparing Declarations and Initializers Built PopGame. Classes Fields and Methods Instantiation using the "new" keyword

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

CISC 1600 Lecture 3.1 Introduction to Processing

Interaction Design A.A. 2017/2018

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

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

CS 106 Winter Lab 03: Input and Output

Chapter 5. Condi.onals

Module 01 Processing Recap

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

CSE120 Wi18 Final Review

CISC 1600, Lab 3.1: Processing

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

Iteration in Programming

Getting Started in Java CIS 110

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

CISC 1600, Lab 2.1: Processing

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Chapter 2: Introduction to C++

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CMPT-166: Sample Midterm

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Class Notes CN19 Class PImage Page

Processing & Arduino in Tandem. Creating Your Own Digital Art Tools

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CSC 220 Object-Oriented Multimedia Programming, Spring 2017

The Processing language. Arduino and Processing.

[ the academy_of_code] Senior Beginners

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:

The Processing language

Final Exam Winter 2013

1 Getting started with Processing

CS110 Introduction to Computing Fall 2016 Practice Exam 1

EP486 Microcontroller Applications

GRAPHICS & INTERACTIVE PROGRAMMING. Lecture 1 Introduction to Processing

Processing Assignment Write- Ups

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

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

Pace University. Fundamental Concepts of CS121 1

01/42. Lecture notes. Processing Basics

Java Basic Programming Constructs

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Computer Science is...

The C++ Language. Arizona State University 1

CS111: PROGRAMMING LANGUAGE II

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

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

Program Fundamentals

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Interaction Design A.A. 2017/2018

2D Shapes. Creative Coding & Generative Art in Processing 2 Ira Greenberg, Dianna Xu, Deepak Kumar

GRAPHICS PROGRAMMING. LAB #3 Starting a Simple Vector Animation

SSOL Language Reference Manual

Introduction to Java

University of Cincinnati. P5.JS: Getting Started. p5.js

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Basic Input and Output

Computer Components. Software{ User Programs. Operating System. Hardware

Design Programming DECO2011

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Introduction to Programming Using Java (98-388)

Transcription:

Variables and Control Structures CS 110 Eric Eaton

Review Random numbers mousex, mousey setup() & draw() framerate(), loop(), noloop() Mouse and Keyboard interaccon Arcs, curves, bézier curves, custom shapes Hue- SaturaCon- Brightness vs. Red- Green- Blue color Decimal, Hex, Binary numbers and colors Example Sketches OpenProcessing website

Variables A name to which data can be assigned A variable name is declared as a specific data type Names must begin with a lever, _ or $ and can container levers, digits, _ and $ boolean bready = true; int i; int j = 12; float fsize = 10.0; color _red = color(255,0,0); String name123 = Fred ; PImage img;

Variable Uses Use a value throughout your program, but allow it to be changed As temporary storage for a intermediate computed result etc

Primi8ve Data Types Type Range Default Bytes boolean { true, false false? byte { 0..255 0 1 int { - 2,147,483,648 0 4.. 2,147,483,647 long { - 9,223,372,036,854,775,808 0 8.. 9,223,372,036,854,775,807 float { - 3.40282347E+38 0.0 4.. 3.40282347E+38 double much larger/smaller 0.0 8 color { #00000000.. #FFFFFFFF black 4 char a single character 'a', 'b', '\u0000' 2

Data Type Conversion Some variable types can be converted to other types Via cas8ng (from Java, the foundacon for Processing) float f = 10.0; int i = (int) f; Processing builds in addiconal type conversion funccons: // binary( ), boolean( ), byte( ), // char( ), float( ), str( ) float f = 10.0; int i; //i = f; i = int(f); // Throws a runtime error println( char(65) ); // Prints the character 'A'

Other "things" Type Range Default Bytes String a series of chars in quotes abc null? PImage an image null? PFont a font for rendering text null? String message = "Hello World!";

Condi8onals: if- statement ProgrammaCc branching if ( boolean_expression ) { statements; // What does this do? void draw() { if ( mousex > 50 && mousey > 50 ) { ellipse( mousex, mousey, 10, 10 );

Rela8onal Expressions < less than > is greater than <= is less than or equal to >= is greater than or equal to == is equivalent!= is not equivalent

Rela8onal Expressions: Examples 1. if ( true ) { 2. if ( 10 > 10 ) { 3. if ( 10 >= 10 ) { 4. if ( 'a' == 'a' ) { 5. if ( 'a'!= 'a' ) { 6. if ( "Bryn Mawr"!= "bryn mawr" ) {

Logical Expressions && logical conjunccon (and) both expressions must be true for conjunccon to be true logical disjunccon (or) either expression must be true for disjunccon to be true! logical negacon (not) true false, false true

Logical Expression Examples 1. if ( (2 > 1) && (3 > 4) ) { 2. if ( ("blah" == "blah") && (1 + 2 == 3) ) { 3. if (!false ) { 4. if (!(1 < -1) ) { 5. if (!(10 < 20) false ) { 6. if (!(10 > 20) && (10 < 20) ) { 7. if ( (true false) && true ) { 8. if ( (true && false) true ) ) { 9.

Condi8onals: if- else- statement if ( boolean_expression ) { statements executed when boolean_expression is true; else { statements executed when boolean_expression is false; // What does this do? void draw() { if ( mousey < 50 ) { println("the sky"); else { println("the ground");

Condi8onals: if- else- if- statement if ( boolean_expression_1 ) { statements; else if ( boolean_expression_2 ) { statements; else if ( boolean_expression_3 ) { statements; else { statements;

void setup() { size(500,500); smooth(); ellipsemode(center); What will this do? void draw() { if (mousex < 250) { stroke(255, 0, 0); if (mousey < 250) { fill(0, 255, 0); else { fill(0, 0, 255); else { stroke(0, 0, 255); if (mousey < 250) { fill(255, 0, 0); else { fill(255); ellipse(mousex, mousey, 50, 30);

void setup() { size( 500, 500 ); smooth(); What does this do? void draw() { if ( mousex > 100 ) { background( 255, 0, 0 ); else if ( mousex > 200 ) { background( 0, 0, 255 );

void setup() { size( 500, 500 ); smooth(); What does this do? void draw() { if ( mousex > 200 ) { background( 255, 0, 0 ); if ( mousex > 100 ) { background( 0, 0, 255 );

Condi8onals: switch- statement Works like a if- else statement. Convenient for large numbers of value tests. switch( expression ) { case label1: statements; break; case label2: statements; break; default: statements; // label1 equals expression // label2 equals expression // Nothing matches

void setup() { size(500, 500); smooth(); What does this do? void draw() { void keypressed() { switch(key) { case 'l': case 'L': println("turning left"); break; case 'r': case 'R': println("turning right"); break;

int positionx = 250; int positiony = 250; int deltax = 0; int deltay = 0; void setup() { size(500, 500); smooth(); void draw() { background(255); positionx = positionx + deltax; positiony = positiony + deltay; if (positionx < 0) positionx = 0; if (positionx > width) positionx = width; if (positiony < 0) positiony = 0; if (positiony > height) positiony = height; void keypressed() { switch (keycode) { case 37: deltax = -2; deltay = 0; break; case 39: deltax = 2; deltay = 0; break; case 38: deltay = -2; deltax = 0; break; case 40: deltay = 2; deltax = 0; break; case 32: deltax = 0; deltay = 0; break; ellipse(positionx, positiony, 50, 50);

Equa8ons of Mo8on (Simplified) s = displacement t = Cme v = velocity a = acceleracon Constant acceleracon (a) s i+1 = s i + v i Δt v i+1 = v i + a Δt

float sx = 0.0; float sy = 0.0; float vx = 1.0; float vy = 1.0; float ay = 0.2; // x position // y position // x velocity // y velocity // y acceleration (gravity) void setup() { size(500, 500); smooth(); ellipsemode(center); void draw() { sx = sx + vx; sy = sy + vy; vy = vy + ay; What does this do? if (sx <= 0.0 sx >= width) vx = -vx; if (sy >= (height-10.0)) vy = -0.9*vy; background(255); ellipse(sx, sy, 20, 20);

Itera8on RepeCCon of a program block Iterate when a block of code is to repeated mulcple Cmes. OpCons The while- loop The for- loop

Itera8on: while- loop while ( boolean_expression ) { statements; // continue; // break; Statements are repeatedly executed while the boolean expression remains true; To break out of a while loop, call break; To stop execucon of statements and start again, call con8nue; All iteracons can be wriven as while- loops.

void setup() { size(500, 500); smooth(); What does this do? float diameter = 500.0; while ( diameter > 1.0 ) { ellipse( 250, 250, diameter, diameter); diameter = diameter * 0.9; void draw() { void setup() { size(500, 500); smooth(); float diameter = 500.0; while ( true ) { ellipse( 250, 250, diameter, diameter); diameter = diameter * 0.9; if (diameter <= 1.0 ) break; void draw() {

An aside Operators +, -, *, / and i++; equivalent to i = i + 1; i += 2; equivalent to i = i + 2; i--; equivalent to i = i 1; i -= 3; equivalent to i = i - 3; i *= 2; equivalent to i = i * 2; i /= 4; equivalent to i = i / 4; i % 3; the remainder a er i is divided by 3 (modulo)

Example factorial = 1; while ( mynumber > 0 ) { factorial *= mynumber; --mynumber; return factorial; 27

The 3 Parts of a Loop int i = 1 ; initialization of loop control variable // count from 1 to 100 while ( i < 101 ) { test of loop termination condition System.out.println( i ) ; i = i + 1 ; modification of loop control variable return 0 ; 28

The for Loop Repetition Structure The for loop handles details of the counter-controlled loop automatically. The initialization of the the loop control variable, the termination condition test, and control variable modification are handled in the for loop structure. for (int i = 1; i < 101; i = i + 1) { initialization modification test 29

for Loop Examples A for loop that counts from 0 to 9: // modify part can be simply i++ for ( i = 0; i < 10; i = i + 1 ) { System.out.println( i ) ; or we can count backwards by 2 s : // modify part can be i -= 2 for ( i = 10; i > 0; i = i - 2 ) { System.out.println( i ) ; 30

When Does a for Loop Initialize, Test and Modify? Just as with a while loop, a for loop initializes the loop control variable before beginning the first loop iteration performs the loop termination test before each iteration of the loop modifies the loop control variable at the very end of each iteration of the loop The for loop is easier to write and read for counter-controlled loops. 31

void setup() { size(500, 500); smooth(); float diameter = 500.0; while ( diameter > 1.0 ) { ellipse( 250, 250, diameter, diameter); diameter = diameter 10.0; void draw() { void setup() { size(500, 500); smooth(); for (float diameter = 500.0; diameter > 1.0; diameter -= 10.0 ) { ellipse( 250, 250, diameter, diameter); void draw() {

void mousepressed() { for (int i = 0; i < 10; i++ ) { print( i ); println(); void draw() { void mousepressed() { for (int i = 0; i < 10; i++ ) { if ( i % 2 == 1 ) continue; print( i ); println(); void draw() {

// for2 float delta = 5.0; float factor = 0.0; void setup() { size(500, 500); void draw() { factor+=0.2; nostroke(); for (float r=0.0; r<height; r+=delta) { for (float c=0.0; c<width; c+=delta) { // Use factor to scale shape float x = map(c, 0.0, 500.0, 0.0, 3.0*TWO_PI); float y = map(r, 0.0, 500.0, 0.0, 3.0*TWO_PI); float shade = map(sin(factor)*sin(x)*sin(y), -1.0, 1.0, 0, 255); // Use factor to shift shade // float x = map(c, 0.0, 500.0, factor, factor+3.0*two_pi); // float y = map(r, 0.0, 500.0, factor, factor+3.0*two_pi); // float shade = map(sin(x)*sin(y), -1.0, 1.0, 0, 255); fill( shade ); rect(r, c, delta, delta);

The break & continue Statements The break & continue statements can be used in while and for loops to cause the remaining statements in the body of the loop to be skipped; then: break causes the looping itself to abort, while continue causes the next turn of the loop to start. In a for loop, the modification step will still be executed. 35

Example break in a for Loop int i; OUTPUT: for (i = 1; i < 10; i = i + 1) { if (i == 5) { 1 2 3 4 break; Broke out of loop at i = 5. System.out.println(i); System.out.println( \nbroke out of loop at i = + i); 36

Example continue in a for Loop int i; for (i = 1; i < 10; i = i + 1) { if (i == 5) { continue; System.out.println(i); System.out.println( Done ); OUTPUT: 1 2 3 4 6 7 8 9 Done. 37

Problem: continue in while Loop // This seems equivalent to for loop // in previous slide but is it?? int i = 1; while (i < 10) { if (i == 5) { continue; System.out.println(i); i = i + 1; System.out.println( Done ); OUTPUT:??? 38

Variable Scope Variable scope: That set of code statements in which the variable is known to the compiler Where it can be referenced in your program. Limited to the code block in which it is defined. A code block is a set of code enclosed in braces ({ ). One interesting application of this principle allowed in Java involves the for loop construct. 39

for-loop index Can declare and initialize variables in the heading of a for loop. These variables are local to the for-loop. They may be reused in other loops. String s = hello world ; int count = 1; for (int i = 0; i < s.length(); i++) { count *= 2; //using 'i' here generates a compiler error 40

Comments Line comment Begins with the symbols // Compiler ignores remainder of the line Used for the coder or for a programmer who modifies the code if (birthyear > currentyear) then... // birth year is invalid Block comment Begins with /* and ends with */ Compiler ignores anything in between Can span several lines Provides documentation for the users of the program /* File: Date Author: Joe Smith Date: 9/1/09 */ Copyright 2008 Pearson Addison- Wesley. All rights reserved 41

text() Strings can be drawn on a sketch using the text() funccon. Can set text posicon, font, size, alignment, Font files are loaded from the data folder. // Set attributes textsize( sizeinpixels ); textalign( {LEFT CENTER RIGHT [,{TOP, BOTTOM, CENTER, BASELINE] ); fill( color ); // Render text text( string, X, Y ); text( string, X, Y, width, height );

// text void setup() { size(500, 500); noloop(); void draw() { // bounding box stroke(0); fill(255); rect(50, 50, 400, 400); // text options fill(0); // black text text("default", 50, 50, 400, 400); textalign(center); text("center", 50, 50, 400, 400); textalign(right); text("right", 50, 50, 400, 400); textalign(center, CENTER); text("center-center", 50, 50, 400, 400); textalign(right, BOTTOM); text("right-bottom", 50, 50, 400, 400); textalign(left, BOTTOM); text("left-bottom", 50, 50, 400, 400);