x - University of Virginia, Department of Computer Science
Download
Report
Transcript x - University of Virginia, Department of Computer Science
2.1 Functions
Functions in Mathematics
x
y
z
Domain
f
f (x, y, z)
Range
Functions in Computer Science
x
y
z
Input
f
Algorithm
f (x, y, z)
Output
•Allows you to clearly separate the tasks in a program.
•Enables reuse of code
Functions (Static Methods)
Java function.
Takes zero or more input arguments.
Returns zero or one output value.
public static void main(String args[])
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().
Princeton I/O libraries: StdIn.readInt(), StdDraw.line(),
StdAudio.play().
User-defined functions: main().
4
Writing Functions in Java
Java functions. Easy to write your own.
2.0
input
f(x) = x
output
1.414213…
Numerically Computing a Square-Root:
Newton-Raphson Method
5
The Newton-Raphson Algorithm
To Compute Square Root of Positive Number c:
{
t = c; //initial estimate of square-root
while(square-root of c is not found) {
if(t == c/t) found square-root of x;
else t = Average of t and c/t;
}
}
6
Function to calculate Square Root using Newton-Raphson Method
2.0
input
f(x) = x
output
1.414213…
7
Functions
Overloading:
•Different argument types
•Different number of arguments
•Different return value is NOT
overloading
overloading
multiple arguments
8
Flow of Control
Key point. Functions provide a new way to control the flow of execution.
9
Flow of Control
Key point. Functions provide a new way to control the flow of execution.
Summary of 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/call by value.”
10
Can a Function Alter Its Arguments?
The short answer for Java: Only if the argument is an array!
(Later we’ll see that objects are like arrays in this way.)
Call by Value.
The argument-variable defined in the function signature is like a
local variable inside the function.
A copy of the value of the actual argument is copied into the
argument-variable when its called
Changes made to the argument-variable inside the function do not
update anything back in the “caller”.
Call by Reference.
The argument-variable defined in the function signature refers to
the same data variable that’s passed when the function is called.
Changes made to the argument-variable inside the function do
update the variable in the “caller”.
11
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.
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;
}
two different
variables with
the same name i
scope of c
scope of epsilon
scope of 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++) {
double x = sqrt(a[i]);
StdOut.println(x);
}
}
}
Best practice: declare variables to limit their scope.
12
Why Are Functions An Important Concept / Technique?
Good Software Design.
Problem-solving: from large problems to smaller sub-problems.
Easier to understand solutions to smaller sub-problems.
Easier to test smaller sub-problems.
We can re-use sub-problem solutions (functions).
Hide details from rest of design. (Example: sqrt. Do we care how
it’s done inside function?)
Abstraction. Reducing or factoring out details so that one can focus
on a few important concepts
// Two functions for getting random values
// between 0 and N-1
public static int randomVal (int N) {
return (int) (Math.random() * N);
}
// between a and b, i.e. in range [a,b)
public static double randomVal(double a, double b) {
return a + Math.random() * (b-a);
}
13
Function Challenge 1a
Q. What happens when you compile and run the following code?
public class Cubes1 {
public static int cube(int i) {
int j = i * i * i;
return j;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
StdOut.println(i + " " + cube(i));
}
}
%
%
1
2
3
4
5
6
javac Cubes1.java
java Cubes1 6
1
8
27
64
125
216
14
Function Challenge 1b
Q. What happens when you compile and run the following code?
public class Cubes2 {
public static int cube(int i) {
int i = i * i * i;
return i;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
StdOut.println(i + " " + cube(i));
}
}
Compiler error: i is already defined
15
Function Challenge 1c
Q. What happens when you compile and run the following code?
public class Cubes3 {
public static int cube(int i) {
i = i * i * i;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
StdOut.println(i + " " + cube(i));
}
}
Compiler error: missing return statement
16
Function Challenge 1d
Q. What happens when you compile and run the following code?
public class Cubes4 {
public static int cube(int i) {
i = i * i * i;
return i;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
StdOut.println(i + " " + cube(i));
}
}
Correct: the i in cube() and the i in main()
are different
17
Function Challenge 1e
Q. What happens when you compile and run the following code?
public class Cubes5 {
public static int cube(int i) {
return i * i * i;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
StdOut.println(i + " " + cube(i));
}
}
Correct and preferred style
18
Dr. Java Demo
Printing An Array + Debugging
19