Switch the screen on/off Go back to last page Go forward one page Find out more details about the advertisement
John Moores University. Main CWIS Site
  

   

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:

    SUM = 0
    NUMBER = 1
10 IF (NUMBER.LE.50) THEN
        SUM = SUM + NUMBER
        NUMBER = NUMBER + 1
        GO TO 10
    END IF

As a 'do' loop:

    SUM = 0
    DO 10 NUMBER=1,50
           SUM = SUM + NUMBER
   10 CONTINUE

 In Derive, this could be written as:

summation(i, sum) := 
    Prog 
      i := 1 
      sum := 0 
      Loop 
        If i > 50 
          RETURN sum 
        sum := sum + i
        i := i + 1

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,

summation(n, i, sum) :=
        Prog 
          i := 1 
          sum := 0 
          Loop 
            If i > n 
                RETURN sum 
            sum :+ i 
            i :+ 1

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 .