CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

Similar documents
CISC 110 Day 1. Hardware, Algorithms, and Programming

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Datatypes, Variables, and Operations

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

Chapter 2: Data and Expressions

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

Fundamentals: Expressions and Assignment

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Algorithms and Programming I. Lecture#12 Spring 2015

Programming Practice (vs Principles)

Such JavaScript Very Wow

Outline. Data and Operations. Data Types. Integral Types

CS 302: Introduction to Programming

The Math Class. Using various math class methods. Formatting the values.

Chapter 17. Fundamental Concepts Expressed in JavaScript

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

The C++ Language. Arizona State University 1

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Full file at

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Chapter 2: Data and Expressions

Welcome to the Primitives and Expressions Lab!

Step by step set of instructions to accomplish a task or solve a problem

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

Chapter 2 Working with Data Types and Operators

Lecture 2 Tao Wang 1

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Getting Started Values, Expressions, and Statements CS GMU

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

CISC 181 Lab 2 (100 pts) Due: March 4 at midnight (This is a two-week lab)

COMP 202 Java in one week

2. Numbers In, Numbers Out

Chapter 2 Elementary Programming

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Hello, World and Variables

Introduction to Computer Science Unit 2. Notes

Objectives. In this chapter, you will:

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

Chapter 2: Data and Expressions

Basics of Java Programming

Module 1: Types and Expressions

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Built-in Types of Data

Simple Java Programming Constructs 4

2 nd Week Lecture Notes

CEN 414 Java Programming

Python Unit

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

LECTURE 02 INTRODUCTION TO C++

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018

CSc Introduction to Computing

CS110: PROGRAMMING LANGUAGE I

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

2. Numbers In, Numbers Out

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Random Numbers; Object-Oriented Programming 11/14/2017

3 The Building Blocks: Data Types, Literals, and Variables

Chapter 1 Histograms, Scatterplots, and Graphs of Functions

Elementary Programming

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

CS112 Lecture: Primitive Types, Operators, Strings

Downloaded from Chapter 2. Functions

1.1 Your First Program! Naive ideal. Natural language instructions.

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

DATA TYPES AND EXPRESSIONS

Programming Basics. Part 1, episode 1, chapter 1, passage 1

Functions, Randomness and Libraries

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Topic 2: C++ Programming fundamentals

CMPT 100 : INTRODUCTION TO

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

ENGR 101 Engineering Design Workshop

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

3. Java - Language Constructs I

AP Computer Science A. Return values

Building Java Programs

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

VBScript: Math Functions

AP CS Unit 3: Control Structures Notes

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

COMP284 Scripting Languages Lecture 2: Perl (Part 1) Handouts

Building Java Programs

HTML5 and CSS3 More JavaScript Page 1

Introduction to Computer Science Unit 2. Notes

Transcription:

CISC 110 Week 3 Expressions, Statements, Programming Style, and Test Review

Today Review last week Expressions/Statements Programming Style Reading/writing IO Test review!

Trace Statements Purpose is to display values or messages in the Output Panel to see the state or progress of a program or animation Very useful for debugging (when your program isn t doing what you want it to do and you don t know why) Only seen by the programmer, trace statements don t do anything to your program

Examples of Trace Statements (try these on your own) trace( 525 ); trace ( Now starting love scene ); trace ( Row + 5 + Col + 7 ); trace ( 5 + 7 ); trace ( 5 + 7 = + 5 + 7 ); 525 Now starting love scene Row 5Col 7 12 5 + 7 = 57 Script Output Window

Variables! Might help to think of variables in programming like your x, y, z variables in math equations Their purpose is to store values Variables in programming are not just numbers (more later)!

Defining Variables - Example var row = 5; row = 8; var next = row + 1; next = next + 1; var s = hi ; var val = 3.5; Script next row val s 10 8 3.5 hi Memory

DataTyping Variables Not required by ActionScript but recommended! Purpose is to explicitly specify the data type that a variable holds in order to reduce the potential for errors when using that variable Ex. You might not want to add two variables of different types together on purpose! You would rather get an error

DataTyping Variables - Example var row: int = 5; row = 8; var next: int = row + 1; next = next + 1; var s: String = hi ; var val: Number = 3.5; Script next row val s 10 8 3.5 hi Memory

Operators Operators allow for operations to occur in a program Numeric String operators Other (assignment, user defined) They are used in an expression to achieve a result

Numeric Operators Operators: + Addition - Subtraction * Multiplication / Division % Mod (integer remainder of division) Expression Result 5 / 2 2.5 5 % 2 1

String Operators (Strings = a string of characters) Operators: + Concatenation += Append trace( Hey + you ); var course = CISC ; var num = 110; course += num; trace( Course is: + course); Script Heyyou Course is: CISC110 Output Window

Escape Sequences Let your format your text Allow you to control what is looks like when it is displayed \n New Line \t Tab \ Single Quote \ Double Quote \\ Backslash trace( Hey\nyou ); trace( Hey\tyou ); trace( Hey \ Kiddo\! ); Script Hey You Hey you Hey Kiddo! Output Window

Comments Allow you to document your code so that when you come back to it later you remember what you did! Also useful for other people who might look at your code (i.e. myself or your TAs) Comments are only seen by the programmer and are not read/execute by the computer They re like sticky notes for your code Also useful for debugging If you don t want all your code to run you can comment it out

Comments Two Ways to Comment Code: // This is a comment /* This is a comment spanning multiple lines */

Data Types Data Type Example Description Number 4.5 Any number int -5 Any integer uint 1 Unsigned integer: any nonnegative integer String hello Text or a string of characters Boolean true true or false

Boolean Variables Variables that store true or false values Ex: var gameover: Boolean; // Creates a Boolean variable gameover = false; // Sets variable to hold value false // (At start of game, it s not over) // Spend time playing the game and then check score gameover = true; // Sets variable to hold value true

Variable Declarations Data Type Number int uint String Boolean Example var x: Number; var y: int; var z: uint; var name: String; var over: Boolean; These only find a space in memory and give it a name. The memory space is not given any value.

Variable Declarations and Assignments Data Type Example Number var x: Number = -55.8; int var y: int = -55; uint var z: uint = 55; String var name: String = MySpace ; Boolean var over: Boolean = false; These find a space in memory and give it a name, and also assign an initial value.

Variable Assignments Data Type Example Number x = -33.657; int y = -20; uint z = 3; String Boolean name = Facebook ; over = true; After a variable has been declared, you can change its value with an assignment statement. However, you must assign the correct type of value for the variable.

Constants You can also define a memory space (like you would define a variable) to hold a constant value This value cannot be changed/re-assigned later in a program Example: const PI : Number = 3.1415; trace( PI ); // 3.1415 will be displayed PI = 3.8; // ERROR

Expressions and Statements An expression is a combination of values, variables, and operators that can be evaluated to obtain a value Examples: 5 + 3 * 2 x / 2 A statement is a command to carry out an action Examples: x = y + 2 trace( x ) // Action: display value // Action: assign a variable a value

Variable Assignment Shortcuts var num: Number = 2; num ++; // same as num = num + 1; num --; // same as num = num 1; num += 3; // same as num = num + 3; num -= 3; // same as num = num 3; num *= 3; // same as num = num * 3; num /= 3; // same as num = num / 3;

Programming Style A useful program must be written so that it may be easily understood and modified, as well as be correct and efficient. This means for example: Use meaningful names for variables, etc. Use indentation and spacing Use comments to say what code is doing A program written with good programming style can be read and interpreted easily by another programmer

Style: Meaningful Variable Names Good names: studentnumber studentnum studentid idnumber Less good names: studentnumber student id stdnum Bad names: s num studentidentificationnumber Why are the good names better?

Style Conventions: Variables Style conventions are used for names in programs, to easily recognize what they represent. The convention for variables is for the first word in the name to start with a lower-case letter Subsequent words in the name start with an uppercase letter (no spaces) Examples: var score : Number = 5; var playername : String = Billy Bob ;

Style Conventions The convention for constants is for the name to be all capitals Words in the same name are separated by an underscore ( _ ) Examples: const PI : Number = 3.1415; const BULLS_EYE : int = 50;

Reading Input from a Text Field Example: Consider an app that will let a user type in a Celsius temperature and will convert it to Fahrenheit. Text Fields required: Input Text Field for input of Celsius temperature Dynamic Text Field for output of Fahrenheit temperature Variables required: var celsius: Number; var fahrenheit: Number;

Reading Input from a Text Field Any text read from a text field is of type String, even when the user types digits To obtain a String s numeric value, convert the String to a number For instance, if the user types a Celsius temperature into a text field called InputTemp, the following stores its numeric value in the variable celsius: var celsius = Number(InputTemp.text);

Using Methods from the Flash Library Remember: To apply a method to an object, specify: <object name>.<method name>(<parameters>) Example: smallbird.gotoandplay(15 );

Writing a number to a Text Field When you write a number to a Text Field, Flash converts it to a String for you You can limit the number of digits displayed after the decimal point with the tofixed method For instance, you could display the variable called fahrenheit in a text field called OutputTemp with only two digits after the decimal place with: OutputTemp.text = fahrenheit.tofixed(2);

Class Methods Not all methods are applied to an object They re just a useful group of methods, for instance those in the Math class. To use these methods, specify: <class name>.<method name>(<parameters>) Example: var x: Number = 2.44; var y: Number = 3.7 x = Math.round( x ); // x is now 2 y = Math.round( y ); // y is now 4

More Math Class Methods Method abs( val ) pow(val1, val2) Description Returns absolute value of val Returns val1 to the power val2 max(val1,val2, ) Returns highest val of val1,val2, min(val1,val2, ) sqrt( val ) random( ) Returns lowest val of val1,val2, Returns square root of val Returns a random number between 0 and.99999999999999

Random Numbers Purpose: To simulate randomness in a program (for instance in a game) The random( ) method in the Math class returns a random value between 0 and.99999999999999 Example: var rand: Number = Math.random( ); trace( "rand = " + rand );

Random Numbers To obtain a random integer between 1 and 6, multiply the result by 5 and then round the result, using the round method, also in the Math class, and add 1 Example: var die1 = Math.round( 5 * Math.random( ) ) + 1; var die2 = Math.round( 5 * Math.random( ) ) + 1; trace( Die 1 = " + die1 ); trace( Die 2 = " + die2 );

Practice with the Math Class Download both MathClass.fla and MathClass.as files from the website (under this week s exercises)

Custom Properties for MovieClips Custom properties can be added to MovieClip instances For example, all MovieClips have a height, but they don t have a speed We could add a speed property to a MovieClip instance called ship1 and set its value with the following line in the constructor function of the.as file: ship1.speed = 5;

Custom Properties for MovieClips Once we have created a custom property in the constructor function, we could use it anywhere later in our script For instance, each time a button is pressed we could move ship1 to the right by the amount specified by the speed property if we added the following line to the button function: ship1.x = ship1.x + ship1.speed;

Test 1 Material Ends Here

CISC 110 Test 1 Info and Practice

CISC110 Test 1 Info When: Tuesday October 6, 6:30-7:30pm (next week!) Where: Here What: Tracing code with variables, numeric expressions, assignment statements, trace statements Writing code with variables, numeric expressions, assignment statements, trace statements Use of methods: For example, Number, String, Math.random, Math.round, Math.min, Math.max, Math.sqrt, Math.abs, Math.pow No text fields, buttons, or movieclips Study custom notes, lecture slides, exercises, labs, assignments, practice questions online

Practice questions: General Instructions (These are the same questions found online) Try to answer these questions by paper and pen like you would in a real test situation. You may choose to verify your answers after in Flash/ActionScript There may be more than 1 way to answer a question!

General Instructions For all of the following questions, assume that the input values have already been read from input text boxes and stored in variables. You will be writing small pieces of code that you can imagine will be placed within either the constructor function or a button-handler function in an.as file as part of a larger project Store the results in variables and display the results in trace statements. Include a description of what each result variable is in your trace statement (e.g., label your output). You can imagine that the results might also be displayed in output text fields, but you don t need to write that code

Question 1 Write code for a Temperature Converter App to convert a Celsius temperature to Fahrenheit. Assume the input temperature has been read from an input text field and has been stored in a Number variable called celsiustemp. The formula for converting from Celsius to Fahrenheit is: F = ( C 9 / 5 ) + 32 For instance, 10 degrees Celsius is 50 degrees Fahrenheit.

Question 2, pg. 1/2 (read all of the question before answering) Write code for a Gas Mileage Calculator App. To calculate gas mileage, a driver can fill up their tank, drive for 100 kilometers, and then fill up the tank again, looking at how many liters of gas they bought to fill up the tank the second time, which is how many liters they used. That is the number of liters of gas per 100 km their vehicle uses. What if they want to drive less than 100 km to determine their gas mileage? Then they would first divide 100 by the number of kilometers they drove. Then they would multiply that amount by the number of liters of gas they used. That gives the number of liters of gas per 100 km their vehicle uses.

Question 2, pg. 2/2 For instance, if they drove 25 km and used 3 litres of gas, the calculation would be 100 / 25 x 3, which equals 12 liters per 100 km. Assume the number of km and the number of liters of gas used have been read from input text fields and are stored in two Number variables called numberofkm and numberofliters. Write code to calculate the number of liters per 100 km.

Question 3 Write code for a Recipe Helper App to do some useful calculations. Assume the number of milliliters for an ingredient has been read from an input text field and has been stored in an int variable called numberofml. Calculate the number of cups, the number of tablespoons and the number of teaspoons in that number of milliliters. There are 250 ml in one cup. There 16 tablespoons in one cup. There are 3 teaspoons in one tablespoon.

Question 4 Write code that uses Math.random and Math.round to simulate throwing two dice. To do so, generate two random numbers in the range 1... 6 and store them in two integer variables called die1 and die2.

Question 5 Write code that uses Math.random and Math.round to simulate drawing a card from a 52-card deck, which has four different suits (hearts, clubs, spades, diamonds) and 13 different values (Ace, 2, 3,..., 10, Jack, Queen, King). Generate one random number in the range 1... 4 to represent the suit and one random number in the range 1... 13 to represent the value, and store them in integer variables called cardsuit and cardvalue You may assume that the numbers 1-4 correspond to hearts, clubs, spades, and diamonds respectively. You do not need to assign them!