Loops
 

Most programs involve repeating a series of instructions over and over until some event occurs.

For example, if we wish to read ten numbers and compute the average, we need a loop to countthe number of numbers we have read.

The flowchart below illustrates a loop that counts from 1 to 10:



 

set total to zero

for K=1 to 10

  total=total+K
NEXT

 

print total


For next loops work the exact number of times needed, in many cases we do not know how many times we want to do something. It is often dependent on the data provided to the program.


Do Loops

 

Imagine we change our problem to read and compute the average of a number of numbers. We won't know how many numbers there are but will read numbers until there are no more.

set average to zero
set count to zero
set total to zero
read number


while ( not end-of-data )
    increment count by 1
    total = total + number
    read number
loop


 if ( count > 0 ) then
    average = total / count
    print average
 end if



 

(c) Shilpa Sayura Foundation 2006-2017