15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

204<br />

Looping a Fixed Number of Times with the FOR-NEXT Loop<br />

Counting by different number ranges is useful only if those numbers mean<br />

something to your program. If you just need to count a fixed number of<br />

times, it’s much clearer to count from 1 to a specific value instead. The following<br />

FOR-NEXT loop actually runs four times (120, 121, 122, and 123):<br />

FOR EmployeeID = 120 TO 123<br />

PRINT EmployeeName<br />

NEXT EmployeeID<br />

Notice that counting from 120 to 123 doesn’t make it clear exactly how many<br />

times the FOR-NEXT loop runs. At first glance, it appears that the FOR-NEXT<br />

loop may repeat only three times.<br />

To clarify exactly how many times the FOR-NEXT loop runs, it’s always much<br />

clearer to count from 1, such as<br />

FOR EmployeeID = 1 TO 4<br />

PRINT EmployeeName<br />

NEXT EmployeeID<br />

Counting by different increments<br />

Normally, the FOR-NEXT loop counts by 1. So consider the following<br />

FOR-NEXT loop:<br />

FOR I = 1 TO 4<br />

PRINT “The value of I = “,I<br />

NEXT I<br />

This FOR-NEXT loop would print<br />

The value of I = 1<br />

The value of I = 2<br />

The value of I = 3<br />

The value of I = 4<br />

If you want to count by a number other than 1, you must define an increment.<br />

So if you want to count by 2, you’d have to define an increment of 2,<br />

such as<br />

FOR I = 1 TO 4 STEP 2<br />

PRINT “The value of I = “,I<br />

NEXT I<br />

This modified FOR-NEXT loop would only print<br />

The value of I = 1<br />

The value of I = 3

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!