Custom Search
 
  

 
CHAPTER 5

WRITING MORE EFFECTIVE AND EFFICIENT PROGRAMS

FOR-NEXT, STEP, DIM, GOSUB, RETURN, Arrays, and Nested Loops

By now you realize the power of a computer is in its capability to do many computations over and over on different data. While a great deal of detail and precision is required when writing a program, once written it can be used again and again. You can see that as problems increase in size and complex-ity, programming becomes more tedious and time consuming, especially if you are limited only to the keywords presented in Chapters 3 and 4.

Fortunately, there are additional keywords:

FOR-NEXTfor simplifying loops

DIMENSION and subscripted variablesfor processing data in tables (arrays of one or more dimensions)

Predefine functionsfor computing commonly used mathematical functions

DEFfor defining your own functions

GOSUB and RETURNto allow the use of subroutines

STOPto terminate program execution anywhere in a program

SIMPLIFYING LOOPS USING FOR-NEXT

In Chapter 4, we saw that loops can be very useful when you have a series of statements you wish to repeat a number of times. BASIC provides two additional keywords that make some loops even easier to construct. They are FOR-TO and NEXT.

A FOR-NEXT loop always begins with a FOR-TO statement and always ends with a NEXT statement. The complete loop is comprised of all statements included between the FOR-TO and the NEXT statements.

Example:

This loop will consist of all statements, from statement number 45 through statement number 75, and it will be executed 5 times.

The FOR-TO statement specifies how many times the loop is to be executed. It must be the first statement in the loop. The FOR-TO statement has a numeric variable, called the running variable, whose value changes each time the loop is executed. The number of executions is determined by specifying the initial and final values for the running variable. In the example, M is the running variable; 1 is the initial value of M, and 5 is the final value of M. Each time through the loop, M is increased by 1. When M equals 5 the program exits the loop.

The NEXT statement consists of a statement number, followed by the keyword, NEXT, followed by a running variable name. This running variable must be the same as the running variable that appears in the corresponding FOR-TO statement.







Western Governors University
 


Privacy Statement - Copyright Information. - Contact Us

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