Consider the following example:
1
2
3
4
5
6
7
8
9
10
11
public class FormalVsActual {
public static int square(int n) { //n is the "formal parameter"
int result = n * n;
return result;
}
public static void main(String[] args) {
int a = 5;
int b = square(a); //whatever is inside the brackets is the "actual parameter"
}
}
In the above example,
square
is n
.square(a)
is a
(5).square(d/20 + e/9)
, the actual parameter would be d/4 + e/9
(100/20 + 36/9 = 9).Before we can truly conquer recursion, it’s critical to understand what happens when a function is called. Consider the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
int ax = 1, ay = 3;
int bx = 6, by = 5;
double d = distance(ax, ay, bx, by);
System.out.println("Distance: "+d);
}
public static double distance(int x1, int y1, int x2, int y2) {
int s1 = square(x2-x1);
int s2 = square(y2-y1);
int sumSquares = s1 + s2;
double result = Math.sqrt(sumSquares);
return result;
}
public static int square(int num) {
int answer = num * num;
return answer;
}
function call is placed on the stack. Note that parameter is null
because we typically do not pass any arguments to main, at least in this unit.
distance
with parameters 1, 3, 6 and 5.Another entry is made for the call to distance
and placed on the call stack.
distance
calls square
with parameter 5
A third entry is made for the call to square
and placed on the stack.
square
returns 25 to distance
Entry for square
is taken off the stack. distance
becomes the active function.
distance
calls square
with parameter 2
A third entry is made for the call to square
and placed on the stack.
square
returns 4 to distance
Entry for square
is taken off the stack. distance
becomes the active function.
distance
calls Math.sqrt
with parameter 29
A third entry is made for the call to Math.sqrt
and placed on the stack.
Math.sqrt
returns 5.38516 to distance
Entry for square
is taken off the stack. distance
becomes the active function.
distance
returns 5.38516 to main
Entry for distance
is taken off the stack. main
becomes the active function.
main
terminatesEntry for main
is taken off the stack. Call stack is now empty. Program has now finished execution.