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

Similar documents
A Balanced Introduction to Computer Science, 3/E

Functions, Randomness and Libraries

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

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Lecture 6: While Loops and the Math Class

Introduction to Computer Science Unit 2. Notes

CS110: PROGRAMMING LANGUAGE I

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini


A Balanced Introduction to Computer Science, 3/E

Coding in JavaScript functions

A Balanced Introduction to Computer Science, 3/E

AP Computer Science A. Return values

AP CS Unit 3: Control Structures Notes

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods / Functions

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

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

Princess Nourah bint Abdulrahman University. Computer Sciences Department

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

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

Building Java Programs

Building Java Programs

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Introduction to Computer Science Unit 2. Notes

TI-84+ GC 3: Order of Operations, Additional Parentheses, Roots and Absolute Value

Building Java Programs

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

Chapter 6 Methods. Dr. Hikmat Jaber

Building Java Programs

Building Java Programs

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Downloaded from Chapter 2. Functions

Building Java Programs

HTML5 and CSS3 More JavaScript Page 1

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Project 2: After Image

JavaScript Basics. The Big Picture

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 4 Mathematical Functions, Characters, and Strings

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

JAVASCRIPT LESSON 4: FUNCTIONS

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

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Computer Programming I - Unit 2 Lecture 1 of 13

Working with JavaScript

A Balanced Introduction to Computer Science, 3/E

Lab 8 CSE 3,Fall 2017

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Language Fundamental of VB.NET Part 1. Heng Sovannarith

A Balanced Introduction to Computer Science


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:

Important Java terminology

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

REVIEW. while (condition) { <body> for (<init> ; <condition> ; <increment>) { } if (condition) { <command> } else { <command> }

Advanced Object Concepts

M e t h o d s a n d P a r a m e t e r s

Such JavaScript Very Wow

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Calculations, Formatting and Conversions

Chapter 16. JavaScript 3: Functions Table of Contents

Random number generation, Math object and methods, HTML elements in motion, setinterval and clearinterval

C Functions. 5.2 Program Modules in C

Functions and Libraries Once upon a time...

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

Programming Practice (vs Principles)

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Chapter 1 Introduction to Computers and the Internet

Using API in Java. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

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

Module 4: Characters, Strings, and Mathematical Functions

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

JavaScript: Functions Pearson Education, Inc. All rights reserved.

Lecture 2: Intro to Java

Topic 12 more if/else, cumulative algorithms, printf

Full file at Tutorial 2: Working with Operators and Expressions

CS177 Python Programming. Recitation 2 - Computing with Numbers

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

CSc 110, Autumn Lecture 10: return values and math

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

Bitwise Operators Objects and Methods

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

CS 302: Introduction to Programming

More About Objects and Methods

Lab 1. Purpose. Assignment. Action Items/Programming Requirements

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

Javascript Lesson 3: Controlled Structures ANDREY KUTASH

The JavaScript Language

Lab 1 Concert Ticket Calculator

S A M P L E C H A P T E R

Lab 2 Population. Purpose. Assignment Lab 2 analyzes population growth of a town as well as compare the population growth of two towns.

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

Transcription:

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN 978-0-13-216675-1 Chapter 7 Functions and Randomness 1

Predefined Functions recall: in mathematics, a function is a mapping from inputs to a single output e.g., the absolute value function: -5 5, 17.3 17.3 in JavaScript, a function is applied to inputs via a function call specify the function name, followed by inputs in parentheses num = parsefloat(document.getelementbyid('numbox').value); in addition to parsefloat, JavaScript has numerous predefined mathematical functions the functest.html page allows you to explore these 2

Math Functions Math.sqrt determines the square root Math.sqrt(9) 9 = 3 Math.sqrt(12.25) 12.25 = 3.5 Math.max determines the maximum of two values Math.max(12, 8.5) 12 Math.max(-3, -8) -3 Math.pow raises a number to a power Math.pow(2, 10) 2 10 = 1024 Math.pow(2, -1) 2-1 = 0.5 Math.pow(9, 0.5) 9 0.5 = 3 Math.min, Math.abs, Math.round, Math.ceil, Math.floor, 3

Rounding Page uses the Math.round function to round a number to 1 digit Math.round(3.14159*10)/10 Math.round(31.4159)/10 31/10 3.1 4

Math.random Math.random generates a pseudo-random number in the range [0 1) pseudo-random refers to the fact that the numbers appear randomly distributed, but are in fact generated by a complex algorithm note: this function has no inputs; it returns a different number each call Math.random() 0.33008525626748814 Math.random() 0.213335955823927 Math.random() 0.8975001737758223 a call to Math.random can be placed in an expression to affect the range 2*Math.random() Math.random() + 1 [0 2) [1 2) 9*Math.random() + 1 [1 10) Math.floor(9*Math.random() + 1) 1, 2, 3,, 9 5

Lucky Number Page displays a random number from the range specified by the text boxes 6

Simplifying buttons consider the button from lucky1.html: the size of ONCLICK attribute makes the button complex and difficult to read plus, must be careful with nested quotes (" " vs. ' ') functions provide a mechanism for simplifying complex buttons such as this recall: functions minimize the amount of detail that has to be considered e.g., can use Math.sqrt without worrying about how it works functions reduce the length and complexity of code e.g., a single call to Math.sqrt replaces the underlying complex algorithm 7

Simple user-defined functions in addition to JavaScript's predefined functions, the user can define new functions in the HEAD section and call them within the page we will explore user-defined functions fully in Chapter 9 for now, the following simple form suffices for simplifying buttons a function definition begins with the word function followed by its name and () a function name should be descriptive of the task being performed lines beginning with // are comments that describe the function's behavior comments are ignored by the interpreter, but make code more user-readable the statements to be executed when the function is called are placed between the curly braces 8

Lucky Number Revisited the code from the button is moved to the userdefined GenerateNumber function SCRIPT tags enclose the function definition in the HEAD as a result, the button is greatly simplified GENERAL ADVICE: if more than one statement is to be associated with a button, define a separate function 9

Example: Dice Simulation suppose we wanted to simulate the roll of a 6-sided die at the click of a button, see a randomly selected roll of a die can use Math.random and Math.floor to generate a random roll between 1 & 6 roll = Math.floor(Math.random()*6) + 1; die images are stored as http://balance3e.com/images/die1.gif, http://balance3e.com/images/die2.gif,, http://balance3e.com/images/die6.gif 10

Example: Dice Simulation the desired die image can be selected using the roll variable ' /die' + roll + '.gif' 11

Example: Slide Show the dice simulation page can be generalized into a random slide show name the slide images using a consistent naming scheme slide1.jpg, slide2.jpg, slide3.jpg, each time the button is clicked, the SelectImage function is called to randomly change the image to select a random slide at the start, make use of the ONLOAD attribute of the BODY tag <body onload="code_to_execute_after_page_loads"> here, call SelectImage after the page loads in order to start with a random image <body onload="selectimage();"> 12

Example: Banner Ads the random slide show page can be generalized into random banner ads name the ad images using a consistent naming scheme ad0.jpg, ad1.jpg, ad2.jpg, the SelectAd function changes the ad to a random image instead of calling the function at the click of a button, can automate using the predefined setinterval function setinterval('javascript_function_call', INTERVAL_IN_MSEC) sets a timer and repeatedly executes the specified function at set intervals <body onload="setinterval('selectad()', 5000);"> will call the function to change the ad image every half second 13

Example: Banner Ads 14