2.1 functions

2.1 functions - A Foundation for Programming 2.1 Functions...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · * * 2 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 build bigger programs and reuse code any program you might want to write 2.1 f x y z f ( x, y, z ) 4 Functions (Static Methods) Java function. ! Takes zero or more input arguments. ! Returns one output value (and/or has side effects —stay tuned). 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() .
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
5 Anatomy of a Java Function Java functions. Easy to write your own. f ( x ) = ! x input 2.0 1.414213… output 6 public class Gambler { public static void main ( String [] args ) { int stake = Integer . parseInt ( args [ 0 ]); int goal = Integer . parseInt ( args [ 1 ]); int trials = Integer . parseInt ( args [ 2 ]); . . . . . . } main is a function ! - that has one argument ( String array args ) - that returns no value (hence void Mumbojumbo Demystification, Part 2 7 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. public class Newton { public static double sqrt(double c) { double epsilon = 1e-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t) > epsilon * t) t = (c/t + t) / 2.0; return t; } public static void main(String[] args) { double[] a = new double[args.length]; for ( int i = 0; i < args.length; i++) a[i] = Double.parseDouble(args[i]); for ( int i = 0; i < a.length; i++) {
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

2.1 functions - A Foundation for Programming 2.1 Functions...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online