0% found this document useful (0 votes)
21 views

Example Loops

Loops can be used for any process that needs to be repeated recursively, not just for computing sums. As an example, a loop can compute the n-fold composition of the function f(x)=x(x-1). The code defines a function nfold that takes inputs x and n. It uses a counter variable a and a loop to apply the function f to x a total of n times, storing the final result of x in the variable nfold.

Uploaded by

JonahJunior
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Example Loops

Loops can be used for any process that needs to be repeated recursively, not just for computing sums. As an example, a loop can compute the n-fold composition of the function f(x)=x(x-1). The code defines a function nfold that takes inputs x and n. It uses a counter variable a and a loop to apply the function f to x a total of n times, storing the final result of x in the variable nfold.

Uploaded by

JonahJunior
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Other uses of 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).

You might also like