Functions Handout
Functions Handout
Functions Handout
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Subroutines<br />
In computer science, a subroutine (also called procedure, method, function, or routine) is a portion<br />
of code within a larger program that performs a specific task and is relatively independent of the<br />
remaining code. The big advantage of a subroutine is that it breaks a program into smaller, easier<br />
to understand pieces. It also makes debugging easier. A subroutine can also be reused in another<br />
program.<br />
The basic idea of a subroutine is that it will take various values, do something with them, and return<br />
a result. In most languages (including all the ones we use in this class) the variables in a subroutine<br />
are local. That means that they do not affect anything outside the subroutine.<br />
Below are three examples in three different languages of a subroutine that solves the equation:<br />
f(x,y) = x 2 sin(y)<br />
In each example the name of the subroutine is george. The subroutine george takes two arguments<br />
x and y, and returns the value of the equation to the main program. In the main program a<br />
variable named junk is assigned the value returned by george. Notice that in the main program the<br />
subroutine george is called using the arguments a and b. Since the variables in the subroutine are<br />
local, you do not have name them x and y in the main program.<br />
AWK<br />
function george(x,y)<br />
{<br />
result = x^2 * sin(y)<br />
return result<br />
}<br />
# Main Part of Program<br />
BEGIN{OFS="\t"}<br />
{<br />
}<br />
END{}<br />
a = 1.2<br />
b = 3.4<br />
junk = george(a,b)<br />
print junk
IDL<br />
FUNCTION george, x, y<br />
END<br />
result = x^2 * sin(y)<br />
return,result<br />
IDL> .run george<br />
IDL> a = 1.2<br />
IDL> b = 3.4<br />
IDL> junk = george(a,b)<br />
IDL> print,junk<br />
Python<br />
def george(x,y):<br />
result = x**2 * sin(y)<br />
return result<br />
# Main Part of Program<br />
def main():<br />
a = 1.2<br />
b = 3.4<br />
junk = george(a,b)<br />
print junk<br />
if __name__ == "__main__":<br />
main()