Most computer languages allows you to break a program into smaller pieces -- subprograms.
Most computer languages have two kinds of subprograms -- functions and subroutines.
Functions, for example SIN(x) compute a single, simple value -- a number, logical value, or a character string -- and return that value.
Function maximum(a, b)
Use:
Suppose you write a program to read, sort ant print 1000 experimental values.
Using the techniques you learned so far, it would be necessary to invent 1000 variable names, 1000 read-statements and so on.
To handle such situations, most computer languages provides arrays.
We want to implement a sorting algorithm.
Bubblesort:
We need also bubblesort(), readN(), printN().
Function readN(soMany):
Subroutine printN(theNumbers, soMany):
Subroutine bubblesort(theNumbers, soMany)
We need also swap().
Subroutine swap(a, b):
For example, n!
1. 1! = 1 2. n! = (n-1)! * n
In a recursive definition one distinguishes between a base rule and a recursive rule. The base rule of a recursive definition describes the term to be defined directly. The recursive rule contains the term to be defined in its own definition.
If we want to calculate n!, we can use the following recursive algorithm:
Function n_factorial(n)
What is the result of:
n_factorial(3): 6 n_factorial(10): 3628800 n_factorial(0): not defined
Another example:
:= 1
:= 1
:=
+
; for 1 n
Function f(n)
What is the result of:
f(0): 1 f(1): 1 f(2): 3 f(3): 4 f(4): 7 f(5): 11
20 extra credits:
Draw a Nassi Shneidermann of a program which prints the permutation of n numbers.
Due: ???
Last modified: 27/July/98 (12:14)