8 - FOR loops and Arrays
For/Next loops:
Add integers from 1 to 100: p. 262
- 'loop using Do While ‘loop using For Next
- CLS ‘clear screen CLS ‘clear screen
- Sum = 0 Sum = 0
- Count = 1 For Count = 1 to 100
- Do While Count <=0 Sum = Sum + Count
- Sum = Sum + Count Next Count
- Count = Count +1 Print "The Sum is "; Sum
- Loop
- Print "The Sum is "; Sum
- Sum Count
- 0 1
- 1 2
- 3 3
- 6 4
- 10 5
- ... ...
- 4950 100
- 5050 101
- Incrementing:
- If no Step is included, Step 1 is assumed
- Stepping by values other than 1 and initializing the loop variable to other than one
- 'Add all even integers
- CLS ' clear screen
- Sum = 0
- For Count = 2 to 100 Step 2
- Sum = Sum + Count
- Next Count
- Print " The Sum is "; Sum
- Sum Count
- 0 2
- 2 4
- 6 6
- 12 8
- ... ...
- 2350 100
- 2450 101
- Values for a For statement:
- Decimal: For Count = .5 to 10 Step .5
Negative: For Count = 10 to 0 Step -1
Variables in a For statement:
Sum = 0
Number = 20
Increment = 1
FOR 1 TO Number Step Increment
Sum = Sum + Number
NEXT Number
- PRINT " The Sum is "; Sum
Expressions as values in a For statement:
For Y = (A * B )/C to P* (F-G) Step C*2
*note: an increment value of zero creates an infinite loop
- Exiting a For loop prematurely: p. 268
- ' Premature exit from a For loop
- ' *************************
- Total.Amount = 0
- FOR Loop.Variable = 1 to 5
- Input "Amount Value"; Amount
- IF Amount <= 0 THEN
- PRINT "Amount = <=0..... Program ending"
- END IF
- Total.Amount = Total. Amount + Amount
- NEXT Loop.Variable
- PRINT : PRINT “Value of Loop.Variable is”; Loop.Variable
Loop.Variable = 1 Total.Amount = 0
2 23
3 39
Number of Iterations for a FOR loop
= (limit - initial value)/ increment value +1
What happens in the following? p. 270
Count = 0
FOR I = 10 TO 1 STEP 2
Count = Count + 1
NEXT I
PRINT| "The loop variable is equal to"; I
PRINT "The FOR loop is executed"; Count; "times"
What if the increment value is -2?
Nested FOR loops: page 271
'Generating the multiplication table
'*****************************
CLS 'clear screen
PRINT " x ! 0 1 2 3 4 5 6 7 8 9 10 11 12"
PRINT "---------------------------------------------------------"
FOR Row = 0 TO 12
PRINT USING "####"; Row ;
FOR Column = 0 to 12
PRINT USING "####"; Row * Column
NEXT Column
PRINT 'move to next line
NEXT ROW
PRINT 'move to next line
Invalid nesting of FOR loops:
FOR A = 1 TO 10
do stuff
FOR B = 1 TO 10
Do other stuff
Next A
Next B
|