| |||||||||||
|
Another example:Sum the integers 1 to 50 inclusive, which is represented mathematically as
which is 1+2+3+...+49+50. This problem demonstrates traditional loops, in particular do and while loops. We construct a loop, executing 50 times, adding the next number to the previous sum.In a traditional language, such as Fortran 77, this could be executed thus: As a 'while' loop:
As a 'do' loop:
In Derive, this could be written as:
Authored in Derive, this is typed thus: summation(i,sum):=Prog(i:=1,sum:=0,Loop(If(i>50,RETURN sum),sum:=sum+i,i:=i+1)) Simplifying, this would give summation() =1275 To extend this routine to sum the first n integers, as well as utilising the more efficient update operators,
Simplifying, this would give summation(40) =820 Note, the above could be slightly improved by the more efficient use of Update Operators. So, instead of writing sum:=sum+i, we could write sum:+i .
| |||||||||||||||||||