Beginning Programs — For-Next Loops

Authors

Publication

Pub Details

Date

Pages

This column is dedicated to you novice programmers to whom BASIC is not so basic. (BASIC is one of the languages your ZX80 understands.) I will also try to simplify concepts in other SYNTAX features so you can get a handle on them and eventually outgrow this column.

For-next loops consist of 2 control statements, FOR.. TO and NEXT. These allow you to tell the computer to do a maximum number of steps in a minimum number of commands when you need the same calculation carried out several times with different variables.

Here’s such a problem: In The 12 Days of Christmas, the singer receives 1 gift the first day, 1 plus 2 more the second, and so on for 12 days. How many gifts in all? (Problem from basic basic by James S. Coan)

To solve it, you must add 1+1+2+1+2+3 . . . +12 , adding each day’s total to the grand total. Let S=sub total for each day, T=grand total, and X=each day. Here’s the program:

 10 LET S=0
20 LET T=0
30 FOR X=1 TO 12
40 LET S=S+X
50 LET T=T+S
60 NEXT X
70 PRINT T

S and T start at 0 because before day 1 there are no gifts (also you must give each number variable a starting value) . X, the day number, is also the number of gifts added to the subtotal each day , 1 through 12 , and this becomes the new subtotal S, At line 50 you add the subtotal to get the new grand total T, At line 60, the computer goes back to line 30 to add new gifts until X=12. Then it goes to line 70 to print the answer. You omit quotes in this statement because you want the value of T, not the letter,

Products

 

Downloadable Media

 

Image Gallery

Source Code

People

No people associated with this content.

Scroll to Top