DOC PREVIEW
STEVENS CS 115 - Functions Lecture Notes

This preview shows page 1-2-20-21 out of 21 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 21 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 10/5/2011 2:32:33 PM Credit: slides adapted by D. Naumann from the authors’ slides, by permission. Fall 2011. Stack frame drawings based on Multimedia Intro to Programming Using Java, by Gries&Gries2.1 Functions f x y z f (x, y, z)3 A Foundation for Programming objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math text I/O assignment statements primitive data types any program you might want to write build bigger programs and reuse code4 Functions (Static Methods) Java function.  Takes zero or more input arguments.  Returns one output value.  Side effects (e.g., output to standard draw). Applications.  Scientists use mathematical functions to calculate formulas.  Programmers use functions to build modular programs.  You use functions for both. Examples.  Built-in functions: Math.random(), Math.abs(), Integer.parseInt().  Our I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play().  User-defined functions: main(). more general than mathematical functions5 Anatomy of a Java Function Java functions. Easy to write your own. f(x) = x input 2.0 1.414213… output6 Flow of Control Key point. Functions provide a new way to control the flow of execution. implicit return statement at end of void function7 Flow of Control Key point. Functions provide a new way to control the flow of execution. What happens when a function is called:  Control transfers to the function code.  Argument variables are assigned the values given in the call.  Function code is executed.  Return value is assigned in place of the function name in calling code.  Control transfers back to the calling code. Note. This is known as "pass by value."8 Scope Scope (of a name). The code that can refer to that name. Ex. A variable's scope is code following the declaration in the block. Best practice: declare variables to limit their scope.9 Function Examples overloading multiple arguments10 Model of function execution: frame … 42 public static void main(String[] args) { 43 int N = Integer.parseInt(args[0]); 44 int count = collect(N); 45 StdOut.println(count); 46 } Next line to execute Class name args11 Execution model: stack of frames 18 public class Coupon { 19 20 // return a random coupon between 0 and N-1 21 public static int getCoupon(int N) { 22 return (int) (Math.random() * N); 23 } 24 25 // return number of cards you collect … 26 public static int collect(int N) { 27 boolean[] found = new boolean[N]; // fount[i] = true if card type i already collected 28 int cardcnt = 0; 29 int valcnt = 0; 30 31 // repeat until you've collected all N … card types 32 while (valcnt < N) { 33 int val = getCoupon(N); // pick a random card 34 cardcnt++; // one more card 35 if (!found[val]) valcnt++; // discovered a new card type 36 found[val] = true; // mark card type as having been collected 37 } 38 return cardcnt; 39 } 40 41 // test client 42 public static void main(String[] args) { 43 int N = Integer.parseInt(args[0]); 44 int count = collect(N); 45 StdOut.println(count); 46 } 47 }12 Execution model: steps in executing a method call 1. Evaluate the arguments of the call and push them onto the top of the stack 2. Draw a frame for the call, at the top of the stack, including those arg values • Fill in the name of the method and set program counter to its first line number • Fill in the scope box: for a static method, this is the name of the class • Add the local variables of the method body • Label the argument values (from step 1) with the parameter names 3. Execute the method body. Whenever a name is referenced in the code, look in the frame for it; if it is not in the , look in the class that’s in the scope box. 4. When execution of the body is finished, erase the frame (pop it from the stack). If execution ended with return expr; then push the value of expr onto the stack There are usually many frames on the stack. There is only one active frame: the one on top of the stack.Digital Audio14 Crash Course in Sound Sound. Perception of the vibration of molecules in our eardrums. Concert A. Sine wave, scaled to oscillate at 440Hz. Other notes. 12 notes on chromatic scale, divided logarithmically.15 Digital Audio Sampling. Represent curve by sampling it at regular intervals. audio CD y(i) = sin2p× i × 44044,100æ è ç ö ø ÷16 Musical Tone Function Musical tone. Create a music tone of a given frequency and duration. Remark. Can use arrays as function return value and/or argument. public static double[] tone(double hz, double seconds) { int SAMPLE_RATE = 44100; int N = (int) (seconds * SAMPLE_RATE); double[] a = new double[N+1]; for (int i = 0; i <= N; i++) { a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLE_RATE); } return a; } y(i) = sin2p× i × hz44,100æ è ç ö ø ÷Standard audio. Library for playing digital audio. Concert A. Play concert A for 1.5 seconds using StdAudio. 17 Digital Audio in Java double[] a = tone(440, 1.5); StdAudio.play(a); library developed for this course (also broadly useful)18 Harmonics Concert A with harmonics. Obtain richer sound by adding tones one octave above and below concert A. 880 Hz 220 Hz 440 Hz19 Harmonics public class PlayThatTuneDeluxe { // return weighted sum of two arrays public static double[] sum(double[] a, double[] b, double awt, double bwt) { double[] c = new double[a.length]; for (int i = 0; i < a.length; i++) c[i] = a[i]*awt + b[i]*bwt; return c; } // return a note of given pitch and duration public static double[] note(int pitch, double duration) { double hz = 440.0 * Math.pow(2, pitch / 12.0); double[] a = tone(1.0 * hz, duration); double[] hi = tone(2.0 * hz, duration); double[] lo = tone(0.5 * hz, duration); double[] h = sum(hi, lo, .5, .5); return sum(a, h, .5, .5); } public static double[] tone(double hz, double t) // see previous slide public static void main(String[] args) // see next slide }20 Harmonics Play that tune. Read in pitches and durations from standard input, and play using


View Full Document

STEVENS CS 115 - Functions Lecture Notes

Download Functions Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Functions Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Functions Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?