|
|
xxxxxxxxxxxxxxxxxx |
BASIC LESSON 3
| |||||||||||||||
| N% | X% | age% | P3% | prime3% | . |
| x& | M& | fudge& | . |
| 32,768 = 215 | , | 2,147,483,648 = 231 . |
Basic will round off an integer variable to the nearest integer. The program
M% = SQR(5)will round off SQR(5) to the nearest integer 2, to produce the output
PRINT "The square root, to the nearest integer, is"; M%
| The square root, to the nearest integer, is 2 . |
Examples :
A = B * H: PRINT "The area is"; A
D = 2 * R: C = 3.14 * D: A = 3.14 * R * R
BEEP: PRINT "Your input is incorrect"
Examples :
| 8 MOD 3 = 2 | 27 MOD 4 = 3 |
| 11 MOD 2 = 1 | 20 MOD 5 = 0 |
Observe that M divides evenly into N whenever N MOD M = 0. The following sequence of statements checks whether an integer M divides evenly into another integer N:
| INPUT "What is the integer to be divided"; N | |
| INPUT "What is the dividing integer"; M | |
| IF N MOD M = 0 THEN | |
| PRINT M; "divides evenly into"; N | |
| ELSE | |
| PRINT M; "does not divide evenly into"; N | |
| END IF | |
| 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 . |
A simple program for doing this is as follows:
| S = 0 | |
| FOR I = 1 TO 10 | |
| S = S + I ^ 2 | |
| NEXT I | |
| PRINT "The sum is"; S | |
How does this program work? It starts off by setting S = 0. Then, letting the loop variable I begin at I = 1, it replaces S by the sum S + 12 = 0 + 1 = 1. Next, setting I = 2, it replaces S by the sum S + 22 = 1 + 4 = 5. Next, setting I = 3, it replaces S by the sum S + 32 = 5 + 9 = 14. The program continues until I = 10, when in the 10th step S is replaced by the sum S + 102. The final value of S then will be the sum you want (namely, 385).
If you want just the sum of the even integers from 1 to 10, say
| 22 + 42 + 62 + 82 + 102 , |
then you modify the program by putting in a STEP condition:
| S = 0 | |
| FOR I = 2 TO 10 STEP 2 | |
| S = S + I ^ 2 | |
| NEXT I | |
| PRINT "The sum is"; S | |
The program starts with I = 2 and proceeds to I = 10 in steps of 2 units; thus it does the calculations only for I = 2, 4, 6, 8, 10. (If a FOR … NEXT loop does not have a step condition, then Basic assumes the step value is + 1.) You can even step backwards (though this is unusual); the statement
| FOR J = 20 to 11 STEP -3 |
instructs Basic to run J through the integers 20, 17, 14, 11.
The starting point and ending point of a loop, as well as the step size, can be variables. The statement
| FOR I = M% to N% STEP K |
instructs Basic to let I run through all the integers from M% to N% in steps of K units.
In a FOR … NEXT loop, Basic always assumes the loop and step variables are integers; thus it is unnecessary to use the % symbol after these variables.