Example Loops
Example Loops
So far we have only seen examples of loops being used in order to compute sums. However loops can be used in any programme that requires some operation to be carried out recursively.
Example: write down a programme that computes the nfold composition of the function f(x)=x(x-1). What we want to compute is f(f(f(f(x)))) (n times) This can be easily done with a loop. We will write a UDF Depending on two variables x and n which computes this. One possible code would be
Function nfold(n as Integer, x as Single) as Single a=1 Do Until a = n + 1 x= x*(x-1) a=a+1 Loop nfold=x End Function
=nfold(30,0.5)
0.122558
If we look at the structure of the loop in more detail we have: The variable a here is just a counter (it counts how many times a=1 we carry out the composition of the function). Do Until a = n + 1 When we write x=f(x) what we are saying is that the next time the x=x*(x-1) loop is carried out the original variable x should be replaced by a=a+1 the new value f(x). Once this process has been Loop carried out n times, the program nfold=x leaves the loop and finally assigns
the last value of x to the value of the function we want to compute (nfold).