Session 06
Procedures and Programming
Repetition with ‘while’:
while “condition” do
“statement sequence”
od;
Note: The sequence of statements are entered by hitting the “shift+ Enter” key after each line. The formatting of this statement ( i.e., indentations, line breaks, etc.) is a matter of taste.
> k:=1;
while k>0 do
sin(k)/k;
k:=k-.2;
od;
Repetition with “for”:
for “counter” from “start” by “increment” to “finish” do
“statement sequence”
od;
> for i from 1 to 4 do
int(x^i*sin(x),x);
diff(%,x);
od;
The following example shows how to create a function as a procedure.
The following example uses the ‘for’ construction within a procedure in order to create a set of polynomials of the form {x, x^2, ...x^n} and then plot them on the same axes.
The procedure creates a function that takes as input the order of the highest power to be plotted.
Note the use of ‘end’ to terminate the procedure definition.
> f:= proc(n)
local s,i;
s:={};
for i from 1 to n do
s:=s union {x^i}
od;
plot(s, x=0..1);
end;
> f(5);
> f(10);
Here is a way to generate some Fibonacci numbers.
> f[1]:=1; f[2]:=1;
for k from 1 to 5 do
f[k+2]:=f[k+1] + f[k]
od;
This procedure computes the first n Fibonacci numbers (n>=2) and prints only the last computed number.
> fib:=proc(n)
local f, k;
f[1]:=1; f[2]:=1;
for k from 1 to n-2 do
f[k+2]:=f[k+1] + f[k]
od;
end:
> fib(100);
Conditional execution with “if then else”. (Again, the line breaks are a matter of style.)
if
"condition"
then
"statement sequence"
else
"statement sequence"
fi;
Let's create the Heaviside function.
> H:=proc(x)
if x>0 then
1
else
0
fi;
end;
> H(-23);
> plot('H'(x), x=-2..2); # What happens without the (' ') ?
Exercises
1. Write a procedure that plots the set {sin(x), sin(2x)...sin(nx)} for a specified n.
2. Write a procedure that prints the first n Fibonacci numbers.
3. Write a procedure that prints all Fibonacci numbers less than a given number.
<< Back - Next >>
|