Custom Search
 
  

 
The following is a program for the flowchart procedure.

Note that line number 40 transfers control to line 70 only when K = 10. Line 60 changes the sequence every time it is executed. Line 50 shows a method to accomplish counting. This statement means that one is added to the current value of K, and the result is assigned to K as its new value. When using a variable as a counter, you should initialize the counter either to zero or some other specified value. In this example the value of K was initially set to 1. This eliminates the possibility of accumulating erroneous totals.

When the program is run, the output will look like this:

There are times when the amount of data we want to process will vary. For example, you might want to keep track of the number of miles per gallon you are getting on your car. A program to solve this problem could be written this way:

The counters M1 and G1 are initialized to zero in lines 20 and 30. They will be used to accumulate total miles (1815) and total gallons (61.5) which will be used to compute the average miles per gallon (29.51).

In this program, we are using a loop (lines 40-80) to read and process sets of data. Look at the READ statement in line 40. On the first pass through the loop, the variable name M will be assigned 485, and G assigned 16. The second pass M will be assigned 520, and G assigned 17.5, and so on until M = 0. Zeros are placed after the data to indicate end of data. They serve as dummy (artificial) data elements which can be tested for in the program to determine when all data has been processed. This allows any number of sets of data to be included in DATA statements. Because the data is read in pairs, two zeros were used to avoid getting an "out of data" error message. The IF-THEN statement in line 50 tests for M = 0. This controls the loop and transfers control (exits the loop) to line 90 when all the input data has been read and processed.

In this way the number of times the loop is executed does not have to be predetermined as in the previous "powers of two" problem where we set the number at 10. This also prevents an "out of data" error message which would be catastrophic in this program. The formula to compute average miles per gallon and the PRINT statement to print the results are outside the loop; therefore, an "out of data" error condition would prevent the program from ever reaching lines 90 and 100.

This program differs from the "Loop using GOTO, READ and DATA" example in the previous section. The statements which did the calculations and printing in that example were inside the loop. Therefore an "out of data" condition was not a catastrophe because all the data had been processed and printed before an "out of data" condition was reached.







Western Governors University
 


Privacy Statement - Copyright Information. - Contact Us

Integrated Publishing, Inc. - A (SDVOSB) Service Disabled Veteran Owned Small Business